Android RSS Reader (Ninja Error) - android

I followed a simple tutorial (http://www.cse.nd.edu/courses/cse40814/www/RSS_Android.pdf) to read RSS feed from a given URL into a listView. I have added the INTERNET permission and the code is error free in Eclipse but it will not show any RSS feed when launched on a device or emulator. I can't make the code anymore simpler, and the feed I am using is stable feed from www.nba.com : http://www.nba.com/rss/nba_rss.xml though i have tested it on several RSS feeds and with still no feed showing.
Any ideas guys?
Main.java
package com.android.simplerssreader;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.android.simplerssreader.data.RssItem;
import com.android.simplerssreader.util.RssReader;
public class Main extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
RssReader rssReader = new RssReader(
"http://www.nba.com/rss/nba_rss.xml");
ListView Items = (ListView) findViewById(R.id.listView1);
ArrayAdapter<RssItem> adapter = new ArrayAdapter<RssItem>(this,
android.R.layout.simple_list_item_1, rssReader.getItems());
Items.setAdapter(adapter);
Items.setOnItemClickListener(new ListListener(rssReader.getItems(),
this));
} catch (Exception e) {
Log.e("SimpleRssReader", e.getMessage());
}
}
}
ListListener.java
package com.android.simplerssreader;
import java.util.List;
import com.android.simplerssreader.data.RssItem;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
public class ListListener implements OnItemClickListener {
List<RssItem> listItems;
Activity activity;
public ListListener(List<RssItem> listItems, Activity activity) {
this.listItems = listItems;
this.activity = activity;
}
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(listItems.get(pos).getLink()));
activity.startActivity(i);
}
}
RssItem.java
package com.android.simplerssreader.data;
public class RssItem {
private String title;
private String link;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
}
RssParseHandler.java
package com.android.simplerssreader.util;
import java.util.ArrayList;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import com.android.simplerssreader.data.RssItem;
public class RssParseHandler extends DefaultHandler {
private List<RssItem> rssItems;
private RssItem currentItem;
private boolean parsingTitle;
private boolean parsingLink;
public RssParseHandler() {
rssItems = new ArrayList<RssItem>();
}
public List<RssItem> getItems() {
return rssItems;
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if ("content-item".equals(qName)) {
currentItem = new RssItem();
} else if ("title".equals(qName)) {
parsingTitle = true;
} else if ("url".equals(qName)) {
parsingLink = true;
}
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if ("content-item".equals(qName)) {
rssItems.add(currentItem);
currentItem = null;
} else if ("title".equals(qName)) {
parsingTitle = false;
} else if ("url".equals(qName)) {
parsingLink = false;
}
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (parsingTitle) {
if (currentItem != null)
currentItem.setTitle(new String(ch, start, length));
} else if (parsingLink) {
if (currentItem != null) {
currentItem.setLink(new String(ch, start, length));
parsingLink = false;
}
}
}
}
RssReader.java
package com.android.simplerssreader.util;
import java.util.List;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import com.android.simplerssreader.data.RssItem;
public class RssReader {
private String rssUrl;
public RssReader(String rssUrl) {
this.rssUrl = rssUrl;
}
public List<RssItem> getItems() throws Exception {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
RssParseHandler handler = new RssParseHandler();
saxParser.parse(rssUrl, handler);
return handler.getItems();
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#000000"
android:orientation="vertical" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000"
android:cacheColorHint="#FFA500"
android:scrollingCache="false"
android:textColor="#ADD8E6" >
</ListView>
</LinearLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.android.simplerssreader"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="16" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.android.simplerssreader.Main"
android:label="#string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
LogCat
01-04 16:22:16.171: E/SimpleRssReader(8685): Couldn't open http://www.nba.com/rss/nba_rss.xml

replace
Log.e("SimpleRssReader", e.getMessage());
with
Log.e("SimpleRssReader", e.getMessage(), e);
you lose the stack trace information.
BTW, your error is that you can't access the network in Android when you are inside the UI Thread (after HoneyComb) : How to fix android.os.NetworkOnMainThreadException?

Related

Dynamically updating list view from XML file at server in Android

I've an XML file present at server, I want to update my list view by using data present at XML file in server and whenever the data is updated in XML, it will reflect automatically in list. I've a code that's working fine separately but when i put the same code in my project it won't work.
Here is my code:
ContactDetail.xml The file to parse
<contact-detail>
<person>
<name>Anshul Thakur</name>
<phone>9882222225</phone>
<email>anshul9#gmail.com</email>
<image-url>https://anshulthakur939.000webhostapp.com/wp-admin/Genesis_App_Data/Contact_Data/me_small.jpg</image-url>
</person>
<person>
<name>A Thakur</name>
<phone>988000005</phone>
<email>anshulth9#gmail.com</email>
<image-url>https://anshulthakur939.000webhostapp.com/wp-admin/Genesis_App_Data/Contact_Data/me_small.jpg</image-url>
</person>
<person>
<name>Arun Thakur</name>
<phone>988111115</phone>
<email>anshulth9#gmail.com</email>
<image-url>https://anshulthakur939.000webhostapp.com/wp-admin/Genesis_App_Data/Contact_Data/me_small.jpg</image-url>
</person>
<person>
<name>Sample</name>
<phone>988222222</phone>
<email>anshul939#gmail.com</email>
<image-url>https://anshulthakur939.000webhostapp.com/wp-admin/Genesis_App_Data/Contact_Data/me_small.jpg</image-url>
</person>
<person>
<name>Sample</name>
<phone>982222222</phone>
<email>anshu9#gmail.com</email>
<image-url>https://anshulthakur939.000webhostapp.com/wp-admin/Genesis_App_Data/Contact_Data/default.jpg</image-url>
</person>
SitesXMLPullParser.java
package com.atechgeek.genesis.XMLPullParser;
import android.content.Context;
import com.atechgeek.genesis.HelperObj.ContactDetail;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Anshul Thakur on 7/27/2017.
*/
public class SitesXMLPullParser
{
static final String KEY_PERSON = "person";
static final String KEY_NAME = "name";
static final String KEY_EMAIL = "email";
static final String KEY_PHONE = "phone";
static final String KEY_IMAGE_URL = "image-url";
public static List<ContactDetail> getContactDetailFromFile(Context ctx)
{
//List to return
List<ContactDetail> contactDetails = new ArrayList<ContactDetail>();
// temp holder for current <person> tag while parsing
ContactDetail curContactDetail = null;
// temp holder for current text value in between opening and closing tags while parsing
String curText = "";
try
{
//get Pull parser
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser parser = factory.newPullParser();
//get input file stream
FileInputStream fileInputStream = ctx.openFileInput("ContactDetail.xml");
//to read file
BufferedReader reader = new BufferedReader(new InputStreamReader(fileInputStream));
//set the file as Input to XMLPullParser
parser.setInput(reader);
//get Initial value of Event
int eventType = parser.getEventType();
//Start Loop to get Events until we reach end of Document
while(eventType!=XmlPullParser.END_DOCUMENT)
{
//get Current Tag
String tagname=parser.getName();
//handle diff EventType
switch (eventType)
{
case XmlPullParser.START_TAG:
if (tagname.equalsIgnoreCase(KEY_PERSON))
{
//if new contact is there <person> ....</person>
curContactDetail = new ContactDetail();
}
break;
case XmlPullParser.TEXT:
//grabs whole of data after starting tag to use in End_tag
curText=parser.getText();
break;
case XmlPullParser.END_TAG:
if(tagname.equalsIgnoreCase(KEY_PERSON))
{
//if </person> then all the contact of 1 person is fetched
//add it to list of Contacts
contactDetails.add(curContactDetail);
}
else if(tagname.equalsIgnoreCase(KEY_NAME))
{
//if </name> occurs then set contactDetails name as contact person name
curContactDetail.setName(curText);
}
else if(tagname.equalsIgnoreCase(KEY_PHONE))
{
//if </phone> occurs
curContactDetail.setPhone(Long.parseLong(curText));
}
else if(tagname.equalsIgnoreCase(KEY_EMAIL))
{
//if </email> occurs
curContactDetail.setEmail(curText);
}
else if(tagname.equalsIgnoreCase(KEY_IMAGE_URL))
{
//if </image-url> occurs
curContactDetail.setImage_url(curText);
}
break;
default:
break;
}
eventType = parser.next();
}
}
catch (Exception e){
e.printStackTrace();
}
return contactDetails;
}
}
Downloader.java
package com.atechgeek.genesis.XMLPullParser;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
/*
* Helper class for downloading a file.
*/
public class Downloader {
//Tag for Log statements
private static String myTag = "StackSites";
//Handler msg that represents we are posting a progress update.
static final int POST_PROGRESS = 1;
/************************************************
* Download a file from the Internet and store it locally
*
* #param URL - the url of the file to download
* #param fos - a FileOutputStream to save the downloaded file to.
************************************************/
public static void DownloadFromUrl(String URL, FileOutputStream fos) { //this is the downloader method
try {
URL url = new URL(URL); //URL of the file
//keep the start time so we can display how long it took to the Log.
long startTime = System.currentTimeMillis();
Log.d(myTag, "download begining");
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
// this will be useful so that you can show a tipical 0-100% progress bar
//int lenghtOfFile = ucon.getContentLength();
Log.i(myTag, "Opened Connection");
/************************************************
* Define InputStreams to read from the URLConnection.
************************************************/
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
Log.i(myTag, "Got InputStream and BufferedInputStream");
/************************************************
* Define OutputStreams to write to our file.
************************************************/
BufferedOutputStream bos = new BufferedOutputStream(fos);
Log.i(myTag, "Got FileOutputStream and BufferedOutputStream");
/************************************************
* Start reading the and writing our file.
************************************************/
byte data[] = new byte[1024];
//long total = 0;
int count;
//loop and read the current chunk
while ((count = bis.read(data)) != -1) {
//keep track of size for progress.
//total += count;
//write this chunk
bos.write(data, 0, count);
}
//Have to call flush or the file can get corrupted.
bos.flush();
bos.close();
Log.d(myTag, "download ready in "
+ ((System.currentTimeMillis() - startTime))
+ " milisec");
} catch (IOException e) {
Log.d(myTag, "Error: " + e);
}
}
}
contactListAdapter.java
package com.atechgeek.genesis.XMLPullParser;
import android.content.Context; import android.graphics.Bitmap; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView;
import com.atechgeek.genesis.HelperObj.ContactDetail; import com.atechgeek.genesis.R; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; import com.nostra13.universalimageloader.core.assist.FailReason; import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import java.util.List;
/** * Created by acer on 7/27/2017. */
public class contactListAdapter extends ArrayAdapter<ContactDetail> {
ImageLoader imageLoader;
DisplayImageOptions options;
public contactListAdapter(Context context, int resource, List<ContactDetail> objects) {
super(context, resource, objects);
//Setup the ImageLoader, we'll use this to display our images
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context).build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
//Setup options for ImageLoader so it will handle caching for us.
options = new DisplayImageOptions.Builder()
.cacheInMemory()
.cacheOnDisc()
.build();
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
RelativeLayout row = (RelativeLayout)convertView;
if(null==row)
{
//no recycled view.....Create one
LayoutInflater inflater = (LayoutInflater)parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row=(RelativeLayout)inflater.inflate(R.layout.row_site, null);
}
//Get our View References
final ImageView iconImg = (ImageView)row.findViewById(R.id.iconImg);
TextView txtName = (TextView)row.findViewById(R.id.txtName);
TextView txtPhoneNo = (TextView)row.findViewById(R.id.txtPhone);
TextView txtEmail = (TextView)row.findViewById(R.id.txtEmail);
final ProgressBar indicator = (ProgressBar)row.findViewById(R.id.progress);
//Initially we want the progress indicator visible, and the image invisible
indicator.setVisibility(View.VISIBLE);
iconImg.setVisibility(View.INVISIBLE);
//Setup a listener we can use to swtich from the loading indicator to the Image once it's ready
ImageLoadingListener listener = new ImageLoadingListener()
{
#Override
public void onLoadingStarted(String s, View view) {
}
#Override
public void onLoadingFailed(String s, View view, FailReason failReason) {
}
#Override
public void onLoadingComplete(String s, View view, Bitmap bitmap) {
indicator.setVisibility(View.INVISIBLE);
iconImg.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingCancelled(String s, View view) {
}
};
//Load the image and use our options so caching is handled.
imageLoader.displayImage(getItem(position).getImage_url(), iconImg,options, listener);
//Set the value of textViews
txtName.setText(getItem(position).getName());
txtPhoneNo.setText(String.valueOf(getItem(position).getPhone()));
txtEmail.setText(getItem(position).getEmail());
return row;
} }
Contact Detail.java
package com.atechgeek.genesis.HelperObj;
/**
* Created by Anshul Thakur on 7/27/2017.
*/
public class ContactDetail
{
private String name;
private String email;
private String image_url;
private long phone;
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
public String getEmail() {
return email;
}
public String getImage_url() {
return image_url;
}
public long getPhone() {
return phone;
}
public void setEmail(String email) {
this.email = email;
}
public void setImage_url(String image_url) {
this.image_url = image_url;
}
public void setPhone(long phone) {
this.phone = phone;
}
}
Now the Main activity Contacts.java
package com.atechgeek.genesis;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import com.atechgeek.genesis.XMLPullParser.SitesXMLPullParser;
import com.atechgeek.genesis.XMLPullParser.Downloader;
import com.atechgeek.genesis.XMLPullParser.contactListAdapter;
import java.io.FileNotFoundException;
public class Contacts extends AppCompatActivity
{
private ListView contactList;
private contactListAdapter mAdapter;
private static ProgressBar bar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
//to add back button
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
contactList = (ListView)findViewById(R.id.contactPersonList);
bar = (ProgressBar)findViewById(R.id.progressBar);
bar.setVisibility(View.VISIBLE);
contactList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
long phoneNumber = mAdapter.getItem(position).getPhone();
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:(+91)"+phoneNumber));
startActivity(intent);
}
});
/*
* If network is available download the xml from the Internet.
* If not then try to use the local file from last time.
*/
if(isNetworkAvailable())
{
ContactFileDownload download = new ContactFileDownload();
download.execute();
}
else
{
mAdapter = new contactListAdapter(getApplicationContext(), -1, SitesXMLPullParser.getContactDetailFromFile(Contacts.this));
contactList.setAdapter(mAdapter);
}
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
private class ContactFileDownload extends AsyncTask<Void, Void, Void>
{
#Override
protected Void doInBackground(Void... params) {
//Download the file
try {
Downloader.DownloadFromUrl("https://anshulthakur939.000webhostapp.com/wp-admin/Genesis_App_Data/contactdetail.xml", openFileOutput("ContactDetail.xml", Context.MODE_PRIVATE));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
//setup our Adapter and set it to the ListView.
mAdapter = new contactListAdapter(Contacts.this, -1, SitesXMLPullParser.getContactDetailFromFile(Contacts.this));
contactList.setAdapter(mAdapter);
bar.setVisibility(View.INVISIBLE);
}
}
}
Its xml activity_contacts.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Contacts" >
<ProgressBar
android:id="#+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:visibility="gone"
/>
<ListView
android:id="#+id/contactPersonList"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
and row_site.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp" >
<ProgressBar
android:id="#+id/progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageView
android:id="#+id/iconImg"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_marginRight="8dp" />
<TextView
android:id="#+id/txtName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/iconImg"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="#+id/txtPhone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/iconImg"
android:textSize="12sp"
android:layout_below="#id/txtName"
/>
<TextView
android:id="#+id/txtEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/iconImg"
android:textSize="12sp"
android:layout_below="#id/txtPhone"
/>
</RelativeLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.atechgeek.genesis">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:hardwareAccelerated="true"
android:icon="#drawable/genesis"
android:label="#string/app_name"
android:largeHeap="true"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".SplashActivity"
android:hardwareAccelerated="false"
android:screenOrientation="portrait"
android:theme="#style/ActivityTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Home" />
<activity
android:name=".WelcomeActivity"
android:screenOrientation="portrait"
android:theme="#style/ActivityTheme" />
<activity
android:name=".SignInActivity"
android:hardwareAccelerated="false"
android:screenOrientation="portrait"
android:theme="#style/ActivityTheme" />
<service android:name=".MyFirebaseMessaging">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#drawable/genesis" />
<activity
android:name=".MyNavDrawer"
android:label="#string/title_activity_my_nav_drawer"
android:screenOrientation="portrait"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".EventActivity"
android:label="#string/title_activity_event"
android:screenOrientation="portrait"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".EventDetailActivity"
android:label="#string/title_activity_event_detail"
android:screenOrientation="portrait"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".ChatWindow"
android:hardwareAccelerated="false"
android:label="#string/chat_title"
android:parentActivityName=".MyNavDrawer">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.atechgeek.genesis.MyNavDrawer" />
</activity>
<activity
android:name=".Contacts"
android:label="#string/contacts_title"
android:parentActivityName=".MyNavDrawer">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.atechgeek.genesis.MyNavDrawer" />
</activity>
</application>
</manifest>
If I create a new project and add these files there then that works fine but when i put it in my project it is not able to work,....
it fetches data only once and then never fetches data from server....
here is the screenshot of project hierarchy ...
hierarchy of project

To Implement these ListActivity to display videos in url

I need to implement these ListActivity.java
ListActivity.java:
package com.sit.fth.activity;
public class ListActivity extends Activity {
private ListView lv;
private String[] groupArray = {"Category1", "Category2", "Category3"};
private String[][] childArray = {{"Test Greater glory Part-3","Greater glory Part-1"},
{"What does","SundayService ( 19_01_14 )"}, {"Greater glory Part-3", "SundayService ( 19_01_14 )Tamil"}};
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.list1);
lv = (ListView) findViewById(R.id.listview);
String[] data = getIntent().getStringArrayExtra("strArray");
AdapterView.OnItemClickListener clickListener = null;
// If no data received means this is the first activity
if (data == null) {
data = groupArray;
clickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(ListActivity.this, ListActivity.class);
intent.putExtra("strArray", childArray[position]);
startActivity(intent);
}
};
}
ArrayAdapter adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, data);
lv.setAdapter(adapter);
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(clickListener);
}
}
list1.java:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/LinearLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ListView
android:id="#+id/listview"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
If I click the Category1 in that ListView.Another ListView shown.
My problem is,If I click the TestGreater Glory Part-3, the video have to display from URL.I doesn't know how to implement that ListActivity Class to the below codings.
strings.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="str_video">VIDEO</string>
<string name="api_host">URL Here</string>
</resources>
YouTubePlayActivity.java:
package com.sit.fth.activity;
public class YoutubePlayActivity extends YouTubeFailureRecoveryActivity {
public static final String DEVELOPER_KEY = "DEVELOPER_KEY_HERE";
private String videoId;
private YouTubePlayerView youTubeView;
private ActionBar actionabar;
private int position;
#Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.youtube_play);
position = getIntent().getExtras().getInt("position");
Bundle bundle = getIntent().getExtras();
videoId = bundle.getString("videoid");
FrameLayout frameLayout = (FrameLayout) findViewById(R.id.youtube_view);
youTubeView = new YouTubePlayerView(this);
frameLayout.addView(youTubeView);
youTubeView.initialize(DEVELOPER_KEY, this);
((TextView) findViewById(R.id.header_title)).setText(bundle
.getString("title"));
actionabar = getActionBar();
//actionabar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionabar.setDisplayHomeAsUpEnabled(true);
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider,
YouTubePlayer player, boolean wasRestored) {
if (!wasRestored) {
try {
if (videoId != null) {
// 2GPfZYwYZoQ
player.cueVideo(videoId);
} else {
Toast.makeText(getApplicationContext(),
"Not a Valid Youtube Video", Toast.LENGTH_SHORT)
.show();
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"Not a Valid Youtube Video", Toast.LENGTH_SHORT).show();
}
}
}
#Override
protected YouTubePlayer.Provider getYouTubePlayerProvider() {
return youTubeView;
}
}
I need to implement that ListActivity.java Class to get the videos shown in the url.
Here's an app that lists categories (that you provide). After clicking some category, it's videos will be loaded from the JSON file and displayed as another ListView.
When you click on a video, it's url and title is sent to the YoutubeActivity. YoutubeActivity then starts a player with that video.
I believe you wanted something more complex but you can add the other functionality (such as getting additional fields from the json) quite easily. If you would want to import categories also, then you'd need another json structure such as array of categories->array of videos.
ListActivity:
package com.example.youtubecatplayer;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Simon on 2014 Jul 08.
*/
public class ListActivity extends Activity {
// Categories must be pre-set
private String[] data = {"Category1", "Category2", "Category3"};
private final String JSONUrl = "http://tfhapp.fathershouse.in/api/video.php";
private final String TAG_VIDEOS = "videos";
private final String TAG_CAT = "video_category";
private final String TAG_URL = "video_url";
private final String TAG_TITLE = "video_title";
private List<String> videoTitles = new ArrayList<String>();
private List<String> videoURLs = new ArrayList<String>();
private ArrayAdapter adapter;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.list1);
ListView listView = (ListView) findViewById(R.id.listview);
Bundle extras = getIntent().getExtras();
AdapterView.OnItemClickListener clickListener = null;
// Category view:
if (extras == null) {
clickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(ListActivity.this, ListActivity.class);
intent.putExtra("categoryName", data[position]);
startActivity(intent);
}
};
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, data);
}
else { // Child view
// Get the category of this child
String categoryName = extras.getString("categoryName");
if (categoryName == null)
finish();
// Populate list with videos of "categoryName", by looping JSON data
new JSONParse(categoryName).execute();
clickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(ListActivity.this, YoutubeActivity.class);
// Send video url and title to YoutubeActivity
intent.putExtra("videoUrl", videoURLs.get(position));
intent.putExtra("videoTitle", videoTitles.get(position));
startActivity(intent);
}
};
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, videoTitles);
}
listView.setAdapter(adapter);
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(clickListener);
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
private String categoryName;
// Constructor // Get the categoryName of which videos will be found
public JSONParse(String category) {
this.categoryName = category;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a loading dialog when getting the videos
pDialog = new ProgressDialog(ListActivity.this);
pDialog.setMessage("Getting Videos...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Get JSON from URL
JSONObject json = jParser.getJSONFromUrl(JSONUrl);
if (json == null)
return null;
try {
// Get video array
JSONArray videos = json.getJSONArray(TAG_VIDEOS);
// Loop all videos
for (int i=0; i<videos.length(); i++) {
JSONObject video = videos.getJSONObject(i);
Log.e("JSON:", "cat: "+video.getString(TAG_CAT)+",title: "+video.getString(TAG_TITLE)+", url: "+video.getString(TAG_URL));
// Check if video belongs to "categoryName"
if (video.getString(TAG_CAT).equals(categoryName)) {
addVideo(video);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return json;
}
private void addVideo(JSONObject video) {
try {
// Add title and URL to their respective arrays
videoTitles.add(video.getString(TAG_TITLE));
videoURLs.add(video.getString(TAG_URL));
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected void onPostExecute(JSONObject json) {
// Close the "loading" dialog
pDialog.dismiss();
if (json == null) {
// Do something when there's no internet connection
// Or there are no videos to be displayed
}
else // Let the adapter notify ListView that it has new items
adapter.notifyDataSetChanged();
}
}
}
// Example JSON video item
// {"videoid":"59","video_type":"Youtube","language":"english","date":"08 Jul 2014",
// "video_title":"What does","video_category":"Category2","video_url":"P84FGn49b4A"},
YoutubeActivity:
package com.example.youtubecatplayer;
import android.app.ActionBar;
import android.os.Bundle;
import android.widget.Toast;
import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerView;
/**
* Created by Simon on 2014 Jul 08.
*/
public class YoutubeActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener{
public static final String DEVELOPER_KEY = "DEV_KEY";
private String videoId;
private ActionBar actionabar;
#Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.youtube_activity);
Bundle bundle = getIntent().getExtras();
videoId = bundle.getString("videoUrl");
this.setTitle(bundle.getString("videoTitle"));
//((TextView) findViewById(R.id.videoTitle)).setText(bundle.getString("videoTitle"));
YouTubePlayerView playerView = (YouTubePlayerView)findViewById(R.id.youtubeplayerview);
playerView.initialize(DEVELOPER_KEY, this);
actionabar = getActionBar();
//actionabar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionabar.setDisplayHomeAsUpEnabled(true);
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player,
boolean wasRestored) {
if (!wasRestored) {
try {
if (videoId != null) {
// 2GPfZYwYZoQ
player.cueVideo(videoId);
} else {
Toast.makeText(getApplicationContext(),
"Not a Valid Youtube Video", Toast.LENGTH_SHORT)
.show();
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"Not a Valid Youtube Video", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider,
YouTubeInitializationResult youTubeInitializationResult) {
}
}
JSONParser:
package com.example.youtubecatplayer;
/**
* Created by Simon on 2014 Jul 08.
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.Charset;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
InputStream input = null;
String jsonStr = null;
JSONObject jsonObj = null;
try {
// Make the request
input = new URL(url).openStream();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(input,
Charset.forName("UTF-8")));
StringBuilder strBuilder = new StringBuilder();
int ch;
while ((ch = reader.read()) != -1)
strBuilder.append((char) ch);
input.close();
jsonStr = strBuilder.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jsonObj = new JSONObject(jsonStr);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jsonObj;
}
}
NOTE: you need internet permission in your AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
And you need to implement the YoutubeAPI into your project.
Download YouTube API
build.gradle compile files('libs/YouTubeAndroidPlayerApi.jar')
EDIT:
I just tried to re-create this project and it worked perfectly. Here's my layout and manifest files, maybe they're causing you trouble.
Android Manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.simas.myapplication" >
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".ListActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".YoutubeActivity"
android:label="#string/app_name" >
</activity>
</application>
</manifest>
youtube_activity.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/youtubeplayerview"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
list1.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".ListActivity">
<ListView
android:id="#+id/listview"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
Don't forget to change the developer key, or you will see a player initialization problem.

Simple xml SAX parser error while retrieve from HTTP

Actually i try to do parse simple XML containing some details using SAX parser and display the result in Spinner. But i con't identify the what is the problem in my problem i mean may be it will be syntax error or my program was not correct. can anyone help me to fix this issues.
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Spinner
android:id="#+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="178dp" />
<Button
android:id="#+id/button1"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/spinner1"
android:layout_alignParentTop="true"
android:layout_alignRight="#+id/spinner1"
android:layout_marginTop="17dp"
android:text="Parse XML using SAX" />
</RelativeLayout>
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/title"
style="#style/spinner" />
styles.xml
<resources xmlns:android="http://schemas.android.com/apk/res/android">
<style name="AppTheme" parent="#android:style/android:Theme" />
<style name="spinner">
<item name="android:layout_width">fill_parent</item>
<item name="android:layout_height">fill_parent</item>
<item name="android:textColor">#0000CD</item>
<item name="android:text">15dp</item>
<item name="android:typeface">monospace</item>
<item name="android:maxHeight">35dp</item>
<item name="android:paddingTop">5dp</item>
<item name="android:paddingBottom">8dp</item>
</style>
</resources>
Mainactivity.class
public abstract class MainActivity extends Activity implements OnClickListener,OnItemSelectedListener {
Button button;
Spinner spinner;
List<Item> item = null;
static final String URL = "http://www.androidituts.com/source/tutorials.xml";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById();
button.setOnClickListener(this);
}
private void findViewById() {
// TODO Auto-generated method stub
button = (Button) findViewById(R.id.button1);
spinner = (Spinner) findViewById(R.id.spinner1);
}
public void onClick(View v) {
item = SAXXMLParser.parse(URL);
ArrayAdapter<Item> adapter = new ArrayAdapter<Item>(this,
R.layout.list_item, item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
Item item = (Item) parent.getItemAtPosition(pos);
Toast.makeText(parent.getContext(), item.getDetails(),
Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
}
Item.java
public class Item {
private String name;
private int id;
private String category;
private String published;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public void setcategory(String category) {
this.category = category;
}
public String getcategory() {
return category;
}
public void setpublished(String published) {
this.published = published;
}
public String getpublished() {
return published;
}
public String getDetails() {
// TODO Auto-generated method stub
String result = id + ": " + name + "\n" + category + "-" + published;
return result;
}
}
SAXXMLParser.java
public class SAXXMLParser {
public static List<Item> parse(String URL) {
List<Item> menu=null;
try {
// create a XMLReader from SAXParser
XMLReader xmlReader = SAXParserFactory.newInstance().newSAXParser()
.getXMLReader();
// create a SAXXMLHandler
SAXXMLHandler saxHandler = new SAXXMLHandler();
// store handler in XMLReader
xmlReader.setContentHandler(saxHandler);
// the process starts
xmlReader.parse(URL);
// get the `Employee list`
menu = saxHandler.getmenu();
} catch (Exception ex) {
Log.d("XML", "SAXXMLParser: parse() failed");
}
// return Employee list
return menu;
}
}
SAXXMLHandler.java
public class SAXXMLHandler extends DefaultHandler {
private List<Item> menu;
private String tempVal;
private Item tempEmp;
public SAXXMLHandler() {
menu = new ArrayList<Item>();
}
public List<Item> getmenu() {
return menu;
}
// Event Handlers
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// reset
tempVal = "";
if (qName.equalsIgnoreCase("item")) {
// create a new instance of employee
tempEmp = new Item();
}
}
public void characters(char[] ch, int start, int length)
throws SAXException {
tempVal = new String(ch, start, length);
}
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (qName.equalsIgnoreCase("item")) {
// add it to the list
menu.add(tempEmp);
} else if (qName.equalsIgnoreCase("id")) {
tempEmp.setId(Integer.parseInt(tempVal));
} else if (qName.equalsIgnoreCase("name")) {
tempEmp.setName(tempVal);
} else if (qName.equalsIgnoreCase("category")) {
tempEmp.setcategory(tempVal);
} else if (qName.equalsIgnoreCase("published")) {
tempEmp.setpublished(tempVal);
}
}
}
Android manifesto.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.xmlspinner"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="8" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.xmlspinner.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
logcat detail
http://i.stack.imgur.com/BpNKV.jpg
I have done changes in codes try below codes...
import java.net.URL;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#SuppressLint("NewApi")
public class XMLParsingDOMExample extends Activity implements AdapterView.OnItemSelectedListener {
ArrayList<String> title;
Button button;
Spinner spinner;
ArrayAdapter<String> from_adapter;
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
title = new ArrayList<String>();
button = (Button) findViewById(R.id.button1);
spinner = (Spinner) findViewById(R.id.spinner1);
spinner.setOnItemSelectedListener(this);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
button.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
parse();
from_adapter=new ArrayAdapter<String>(getBaseContext(),android.R.layout.simple_spinner_item, title);
from_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(from_adapter);
}
});
}
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
Toast.makeText(parent.getContext(), ""+spinner.getSelectedItem().toString().trim(),
Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
}
protected void parse() {
// TODO Auto-generated method stub
try {
URL url = new URL(
"http://www.androidituts.com/source/tutorials.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("item");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("id");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
NodeList websiteList = fstElmnt.getElementsByTagName("name");
Element websiteElement = (Element) websiteList.item(0);
websiteList = websiteElement.getChildNodes();
NodeList websiteList1 = fstElmnt.getElementsByTagName("category");
Element websiteElement1 = (Element) websiteList1.item(0);
websiteList1 = websiteElement1.getChildNodes();
NodeList websiteList2 = fstElmnt.getElementsByTagName("published");
Element websiteElement2 = (Element) websiteList2.item(0);
websiteList2 = websiteElement2.getChildNodes();
title.add(((Node) nameList.item(0)).getNodeValue()+":"+((Node) websiteList.item(0)).getNodeValue() +"\n"+((Node) websiteList1.item(0)).getNodeValue()+"-"+((Node) websiteList2.item(0)).getNodeValue());
}
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
}
}
Now you can get all the details in that spinner...
You can't Performing Network Operations ON GUI thread so you have to create a thread to fitch and parse data from URL.
public void onClick(View v) {
new Thread(new Runnable() {
#Override
public void run() {
item = SAXXMLParser.parse(URL);
spinhandler.sendEmptyMessage(0);
}
}).start();
}
Create Handler
private Handler spinhandler = new Handler() {
#Override
public void handleMessage(Message msg) {
if(msg.what == 0) {
ArrayAdapter<Item> adapter = new ArrayAdapter<Item>(MainActivity.this, R.layout.list_item, item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(MainActivity.this);
}
}
};
When try to put data in Item Object the Item object equal null so you have to intialize the object before start access it
if (qName.equalsIgnoreCase("id")) {
tempEmp = new Item();
tempEmp.setId(Integer.parseInt(tempVal));
}

Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views

I am trying to write a program to parse the given xml. However, it throws that error message:"Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. "
This is my code
package com.example.xmlparserdeneme;
import java.io.IOException;
import java.util.ArrayList;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.ListView;
public class MainActivity extends Activity {
ArrayList<String> titles = new ArrayList<String>();
Context ctx = this;
CustomAdapter adapter = null;
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
((Activity) ctx).setContentView(R.layout.activity_main);
new parseXML().execute();
Log.i("info2", titles.toString());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
class parseXML extends AsyncTask<String, Void, String> {
MySaxHandler handler;
#Override
protected String doInBackground(String... params) {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser parser = null;
try {
parser = spf.newSAXParser();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
handler = new MySaxHandler();
try {
parser.parse(
"/xmlParserDeneme/src/Database.xml",
handler);
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Log.i("info", titles.toString());
return "a";
}
#Override
protected void onPostExecute(String result) {
lv = (ListView) findViewById(R.id.listView);
lv.setAdapter(new CustomAdapter(titles, ctx));
}
public ArrayList<String> getArray() {
return titles;
}
public class MySaxHandler extends DefaultHandler {
StringBuffer chars;
public void startElement(String uri, String localName,
String qName, Attributes atts) {
chars = new StringBuffer();
}
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (localName.equalsIgnoreCase("description"))
titles.add(chars.toString());
}
public void characters(char ch[], int start, int length) {
chars.append(new String(ch, start, length));
}
}
}
}
I am new at android, I don't know where to change.
I'd be appreciated if anyone tell me how to fix it?
Please write this code in oncreate method .
ctx = this;
And remove this code.
((Activity) ctx).setContentView(R.layout.activity_main);

how to use Layout to display the result get from XML

I am A new guy in Android. I try to develop a list that can show the song name and author at the same line. The source data is from a online XML file
The following is the code I try to use in my program.
However, I only be able to display the author name in the list.
I would to ask how I should modify the code so that I can show the song name and author at the same line in the list?
The Format of online XML file I try to read
<recipes>
<song>
<id>1</id>
<title>Sing A Song</title>
<songs_author>ACM</songs_author>
</song>
<song>
<id>2</id>
<title>DO Re Me</title>
<songs_author>BBC/songs_author>
</song>
</recepies>
src/com.mobile/SongsActivity
package com.mobile;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class SongsActivity extends Activity implements OnItemClickListener {
protected static final int DIALOG_KEY = 0;
ListView mListView;
Button mClear;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
this.setProgressBarIndeterminateVisibility(false);
setContentView(R.layout.Songs);
mListView = (ListView) findViewById(R.id.listView1);
mListView.setTextFilterEnabled(true);
mListView.setOnItemClickListener(this);
LoadRecipesTask1 mLoadRecipesTask = new LoadRecipesTask1();
mLoadRecipesTask.execute("http://123.com/mobile/Songs_list.php");
mClear = (Button) findViewById(R.id.button3);
mClear.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mListView.setAdapter(null);
}
});
}
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Datum datum = (Datum) mListView.getItemAtPosition(position);
Uri uri = Uri.parse("http://123.com/mobile/Songs.php?Songsid=" + datum.getId());
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
this.startActivity(intent);
}
public static ArrayList<Datum> parse(String url) throws IOException, XmlPullParserException {
final ArrayList<Datum> results = new ArrayList<Datum>();
URL input = new URL(url);
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(input.openStream(), null);
int eventType = xpp.getEventType();
String currentTag = null;
Integer id = null;
String title = null;
String Songs_author = null;
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
currentTag = xpp.getName();
} else if (eventType == XmlPullParser.TEXT) {
if ("id".equals(currentTag)) {
id = Integer.valueOf(xpp.getText());
}
if ("title".equals(currentTag)) {
title = xpp.getText();
}
if ("Songs_author".equals(currentTag)) {
Songs_author = xpp.getText();
}
} else if (eventType == XmlPullParser.END_TAG) {
if ("song".equals(xpp.getName())) {
results.add(new Datum(id, title, Songs_author));
}
}
eventType = xpp.next();
}
return results;
}
protected class LoadRecipesTask1 extends AsyncTask<String, Void, ArrayList<Datum>> {
#Override
protected void onPreExecute() {
SongsActivity.this.setProgressBarIndeterminateVisibility(true);
}
#Override
protected ArrayList<Datum> doInBackground(String... urls) {
ArrayList<Datum> datumList = new ArrayList<Datum>();
try {
datumList = parse(urls[0]);
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
return datumList;
}
#Override
protected void onPostExecute(ArrayList<Datum> result) {
mListView.setAdapter(new ArrayAdapter<Datum>(SongsActivity.this, R.layout.list_item, result));
//SongsActivity.this.setProgressBarIndeterminateVisibility(false);
}
}
}
src/com.mobile/Datum
package com.mobile;
public class Datum {
int id;
String title;
String songs_author;
public Datum(int id, String title, String songs_author) {
this.id = id;
this.title = title;
this.songs_author= songs_author;
}
public String toString() {
return songs_author;
}
public int getId() {
return id;
}
public String getTitle() {
return title;
}
public String get Songs_author() {
return Songs_author;
}
}
res/layout/songs.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="fill_parent"
android:layout_height="wrap_content">
<Button android:text="Refresh 1" android:id="#+id/button1"
android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1"></Button>
<Button android:text="Clear" android:id="#+id/button3"
android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1"></Button>
</LinearLayout>
<ListView android:id="#+id/listView1" android:layout_height="fill_parent"
android:layout_width="fill_parent"></ListView>
</LinearLayout>
res/layout/list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="16sp" >
</TextView>
Just make Custom List View using array adapter.
refer this example..
http://www.softwarepassion.com/android-series-custom-listview-items-and-adapters/
The web is full of tutorial and example of ListView using Custom Adapter. You will have to spend some time trying to learn them. No shortcuts. You can one of them here or you can select one of the books from Amazon.

Categories

Resources