package com.example.nasadailyimage;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.ImageView;
import android.widget.TextView;
public class NasaDailyImage extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nasa_daily_image);
IotdHandler handler = new IotdHandler();
System.out.println("handler object created");
Log.d("NasaDailyImage","handler object created");
new ConfigParser().execute();//here i have called execute on my AsyncTaskclass
// handler.processFeed();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.nasa_daily_image, menu);
return true;
}
}
and my ConfigParser class
import java.io.InputStream;
import java.net.URL;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.os.AsyncTask;
import android.util.Log;
public class ConfigParser extends AsyncTask<Void, Void,Void > {
private String url="http://www.nasa.gov/rss/dyn/image_of_the_day.rss";
#Override
protected Void doInBackground(Void... params) {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader reader = parser.getXMLReader();
IotdHandler handler=new IotdHandler();
reader.setContentHandler(handler);
InputStream inputStream = new URL(url).openStream();
reader.parse(new InputSource(inputStream));
}
catch (Exception e)
{
Log.d("IotdHandler", "Exception");
e.printStackTrace();
}
return null;
}
}
and my IotdHandler Class
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
public class IotdHandler extends DefaultHandler {
private String url="http://www.nasa.gov/rss/dyn/image_of_the_day.rss";
private boolean inUrl = false;
private boolean inTitle = false;
private boolean inDescription = false;
private boolean inItem = false;
private boolean inDate = false;
private Bitmap image = null;
private String title = null;
private StringBuffer description = new StringBuffer();
private String date = null;
private String imageUrl;
private Bitmap getBitmap(String url) {
try {
HttpURLConnection connection = (HttpURLConnection)new URL(url).openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(input);
input.close();
return bitmap;
}
catch (IOException ioe)
{ ioe.printStackTrace(); }
return null;
}
public void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException {
if (localName.equals("enclosure"))
{ inUrl = true;
imageUrl=attributes.getValue("url");
System.out.println(imageUrl);
}
else { inUrl = false; }
if (localName.startsWith("item"))
{ inItem = true; }
else if (inItem) {
if (localName.equals("title"))
{ inTitle = true;
System.out.println("invtitle");}
else { inTitle = false; }
if (localName.equals("description"))
{ inDescription = true;
System.out.println("indiscription");}
else { inDescription = false; }
if (localName.equals("pubDate"))
{ inDate = true;
System.out.println("dtae");}
else { inDate = false; }
}
}
public void characters(char ch[], int start, int length) {
String chars = new String(ch).substring(start, start + length);
if (inUrl && url == null) { image = getBitmap(imageUrl); }
if (inTitle && title == null) { title = chars; }
if (inDescription) { description.append(chars); }
if (inDate && date == null) { date = chars; }
}
public Bitmap getImage() { return image; }
public String getTitle() { return title; }
public StringBuffer getDescription() { return description; }
public String getDate() { return date; }
}
So basically I want to get daily image updates from NASA, but in my program everything is returning null I don't know what I am trying wrong, my xml file is not parsing to avoid the NetworkOnMainTHread I have also used Async class, any help.
Here is the code parsing xml rss feed...
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.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#SuppressLint("NewApi")
public class XMLParsingDOMExample extends Activity {
ArrayList<String> title;
ArrayList<String> description;
ArrayList<String> pubDate;
ItemAdapter adapter1;
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
ListView list = (ListView) findViewById(R.id.list);
title = new ArrayList<String>();
description = new ArrayList<String>();
pubDate = new ArrayList<String>();
parse();
adapter1 = new ItemAdapter(this);
list.setAdapter(adapter1);
}
protected void parse() {
// TODO Auto-generated method stub
try {
URL url = new URL(
"http://www.nasa.gov/rss/dyn/image_of_the_day.rss");
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("title");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
title.add(((Node) nameList.item(0)).getNodeValue());
NodeList websiteList = fstElmnt.getElementsByTagName("description");
Element websiteElement = (Element) websiteList.item(0);
websiteList = websiteElement.getChildNodes();
description.add(((Node) websiteList.item(0)).getNodeValue());
NodeList websiteList1 = fstElmnt.getElementsByTagName("pubDate");
Element websiteElement1 = (Element) websiteList1.item(0);
websiteList1 = websiteElement1.getChildNodes();
pubDate.add(((Node) websiteList1.item(0)).getNodeValue());
}
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
}
class ItemAdapter extends BaseAdapter {
final LayoutInflater mInflater;
private class ViewHolder {
public TextView title_text;
public TextView des_text;
public TextView date_text;
}
public ItemAdapter(Context context) {
// TODO Auto-generated constructor stub
super();
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
//#Override
public int getCount() {
return title.size();
}
//#Override
public Object getItem(int position) {
return position;
}
//#Override
public long getItemId(int position) {
return position;
}
//#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
final ViewHolder holder;
if (convertView == null) {
view = mInflater.inflate(R.layout.mainpage_listitem_activity, parent, false);
holder = new ViewHolder();
holder.title_text = (TextView) view.findViewById(R.id.title_text);
holder.des_text = (TextView) view.findViewById(R.id.des_text);
holder.date_text = (TextView) view.findViewById(R.id.date_text);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.title_text.setText(""+title.get(position));
holder.des_text.setText(""+Html.fromHtml(description.get(position)));
holder.date_text.setText(""+pubDate.get(position));
return view;
}
}
}
I posted a Gist on how to do this using the android-rss library with the droidQuery library:
final RSSHandler handler = new RSSHandler(new RSSConfig());
$.ajax(new AjaxOptions().url(options.url())
.type("GET")
.dataType("XML")
.context(this)
.SAXContentHandler(handler)
.success(new Function() {
#Override
public void invoke($ droidQuery, Object... params) {
RSSFeed feed = handler.feed();
//TODO: handle feed here.
}
}));
Make an interface in your project first
public interface mMyInterface {
void processFinish(String response);
}
Then in your AsyncTaskClass do the following modifications
public class ConfigParser extends AsyncTask<Void, Void,Void > {
public mMyInterface delegate=null;
private String url="http://www.nasa.gov/rss/dyn/image_of_the_day.rss";
#Override
protected Void doInBackground(Void... params) {
try {
//Log.i("inJSONPARSERCLASS","success");
DefaultHttpClient client=new DefaultHttpClient();
HttpPost post=new HttpPost(url);
HttpResponse httpResponse=client.execute(post);
HttpEntity entity=httpResponse.getEntity();
is=entity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
catch (Exception e) {
Log.e("Connection Error", "Error " + e.toString());
}
try {
BufferedReader reader=new BufferedReader(new InputStreamReader(is, "iso-8859-1"),8);
StringBuilder sb=new StringBuilder();
String line=null;
while((line=reader.readLine())!=null){
sb.append(line+"\n");
}
is.close();
xml=sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
Log.i("main XML",""+xml);
return xml;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
delegate.processFinish(result);
}
}
Now in your class which is extending the activity , implement the interface mMyInterface , this will override its method processFinish(String response), now use "response" as a string and pass it to the class where the parsing is being done
#Override
public void processFinish(String response) {
String xml=response;
//do SAXparsing stuff here, parse this xml string which contains the whole data u need to
parse
}
I hope this hint will work out for you very well. :)
Related
I am trying to make an app where I want my app, on launch, to display a grid of popular movie posters. The movie posters are downloaded from TheMovieDataBase API. I then use Picasso to load the images. For the GridView I am also using a custom adapter. I am not able to understand how to do it. Here is what I have done up till now
MovieFragment.java
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class MovieFragment extends Fragment {
//ArrayAdapter<String> mMovieAdapter;
String[]movieId,movieTitle,movieOverview,
movieReleaseDate,
moviePosterPath,movieVoteAverage;
public MovieFragment() {
}
MovieAdapter mMovieAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
mMovieAdapter = new MovieAdapter(getActivity());
GridView listView = (GridView) rootView.findViewById(R.id.gridView);
listView.setAdapter(mMovieAdapter);
updateMovie();
return rootView;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Inflate the menu; this adds items to the action bar if it is present.
inflater.inflate(R.menu.menu_fragment, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_refresh) {
updateMovie();
return true;
}
return super.onOptionsItemSelected(item);
}
private void updateMovie() {
FetchMovieTask movieTask = new FetchMovieTask();
movieTask.execute();
}
class FetchMovieTask extends AsyncTask<Void, Void, List<String>> {
private final String LOG_TAG = FetchMovieTask.class.getSimpleName();
#Override
protected List<String> doInBackground(Void... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String movieJsonStr = null;
try {
URL url = new URL("http://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&api_key=c20129fdf73b5df3ab44548ad7f73586");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
movieJsonStr = buffer.toString();
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
try {
return getMovieDataFromJson(movieJsonStr);
} catch (JSONException j) {
Log.e(LOG_TAG, "JSON Error", j);
}
return null;
}
private List<String> getMovieDataFromJson(String forecastJsonStr)
throws JSONException {
JSONObject movieJson = new JSONObject(forecastJsonStr);
JSONArray movieArray = movieJson.getJSONArray("results");
List<String> urls = new ArrayList<>();
for (int i = 0; i < movieArray.length(); i++) {
JSONObject movie = movieArray.getJSONObject(i);
urls.add("http://image.tmdb.org/t/p/w185" + movie.getString("poster_path"));
}
return urls;
}
#Override
protected void onPostExecute(List<String> strings) {
mMovieAdapter.replace(strings);
}
}
class MovieAdapter extends BaseAdapter {
private final String LOG_TAG = MovieAdapter.class.getSimpleName();
private final Context context;
private final List<String> urls = new ArrayList<String>();
public MovieAdapter(Context context) {
this.context = context;
Collections.addAll(urls, moviePosterPath);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = new ImageView(context);
}
ImageView imageView = (ImageView) convertView;
String url = getItem(position);
Log.e(LOG_TAG," URL "+url);
Picasso.with(context).load(url).into(imageView);
return convertView;
}
#Override
public int getCount() {
return urls.size();
}
#Override
public String getItem(int position) {
return urls.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public void replace(List<String> urls) {
this.urls.clear();
this.urls.addAll(urls);
notifyDataSetChanged();
}
}
}
When I run this code it shows a NullPointerException and a RuntimeException
java.lang.RuntimeException: Unable to start activity ComponentInfo
{com.codesetters.verader/com.codesetters.verader.MainActivity}: java.lang.NullPointerException atandroid.app.ActivityThreadperformLaunchActivity(ActivityThread.java:2404)
Caused by: java.lang.NullPointerException atjava.util.Collections.addAll(Collections.java:2582)
How can I resolve them?
Please Help
You're getting this error because you've used moviePosterPath here :
Collections.addAll(urls, moviePosterPath);
but you've not initialized it anywhere. Initialize it with some value and it should solve the error.
The null pointer could be because the String array moviePosterPath is not initialized. and you are ussing it in Collections.addAll
This is how to initialize an array. Anyway I recommend you to use ArrayList
String[] moviePosterPath = new String[N];
Currently I am developing a Popular Movies app by udacity and stuck at loading images from the MovieDb api. I have also took reference from this thread Picasso Images are not loading in Gridview Android but no use.
Here is my fragment file:
package com.akshitjain.popularmovies;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* A placeholder fragment containing a simple view.
*/
public class MainActivityFragment extends Fragment {
ImageAdapter mMoviesAdapter;
public MainActivityFragment() {
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
setHasOptionsMenu(true);
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_main, container, false);
GridView gridview = (GridView) rootView.findViewById(R.id.grid_view_movies);
mMoviesAdapter = new ImageAdapter(getActivity());
gridview.setAdapter(mMoviesAdapter);
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Toast.makeText(getActivity(), "" + position,
Toast.LENGTH_SHORT).show();
}
});
return rootView;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_mainfragment,menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == R.id.action_refresh){
String sortOrder = "popularity.desc";
new FetchMoviesTask().execute(sortOrder);
return true;
}
return super.onOptionsItemSelected(item);
}
public class FetchMoviesTask extends AsyncTask<String, Void, String[]> {
private final String LOG_TAG = FetchMoviesTask.class.getSimpleName();
private String[] getMoviesDataFromJson(String moviesJsonStr)
throws JSONException {
final String TMDB_RESULTS = "results";
final String TMDB_POSTER = "poster_path";
JSONObject moviesJson = new JSONObject(moviesJsonStr);
JSONArray moviesArray = moviesJson.getJSONArray(TMDB_RESULTS);
String[] resultStrs = new String[moviesArray.length()];
for(int i=0;i<moviesArray.length();++i) {
JSONObject movieObject = moviesArray.getJSONObject(i);
resultStrs[i] = movieObject.getString(TMDB_POSTER);
}
return resultStrs;
}
#Override
protected String[] doInBackground(String... params) {
// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String moviesJsonStr;
String apiKey = BuildConfig.THE_MOVIE_DB_API_KEY;
try {
// Construct the URL for the TheMovieDb query
// Possible parameters are available at TheMovieDb API page
final String MOVIES_BASE_URL = "http://api.themoviedb.org/3/discover/movie?";
final String SORT_PARAM = "sort_by";
final String API_KEY = "api_key";
Uri builtUri = Uri.parse(MOVIES_BASE_URL).buildUpon()
.appendQueryParameter(SORT_PARAM,params[0])
.appendQueryParameter(API_KEY,apiKey)
.build();
URL url = new URL(builtUri.toString());
Log.v(LOG_TAG,"BuiltUri: " + builtUri.toString());
// Create the request to TheMovieDb, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuilder buffer = new StringBuilder();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line).append("\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
moviesJsonStr = buffer.toString();
Log.v(LOG_TAG,"Movies Json String: " + moviesJsonStr);
} catch (IOException e) {
Log.e("MainActivityFragment", "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attempting
// to parse it.
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("MainActivityFragment", "Error closing stream", e);
}
}
}
try{
return getMoviesDataFromJson(moviesJsonStr);
}catch (JSONException e){
Log.e(LOG_TAG,e.getMessage(),e);
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String[] strings) {
if(strings != null){
mMoviesAdapter.clear();
for(String moviesStr:strings){
mMoviesAdapter.add(moviesStr);
}
}
mMoviesAdapter.notifyDataSetChanged();
super.onPostExecute(strings);
}
}
}
Here is my custom adapter file:
package com.akshitjain.popularmovies;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
public class ImageAdapter extends BaseAdapter {
private final String LOG_TAG = ImageAdapter.class.getSimpleName();
private Context mContext;
List<String> list = new ArrayList<>();
public ImageAdapter(Context c) {
this.mContext = c;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.grid_item_movies, parent, false);
}
final String POSTER_BASE_URL = " http://image.tmdb.org/t/p/";
final String POSTER_SIZE = "w185";
ImageView moviePoster = (ImageView) convertView.findViewById(R.id.grid_item_movie_image);
final String POSTER_FINAL_URL = POSTER_BASE_URL + POSTER_SIZE + list.get(position);
Log.v(LOG_TAG,"Poster Urls: " + POSTER_FINAL_URL);
Picasso.with(mContext).load(POSTER_FINAL_URL).into(moviePoster);
return convertView;
}
public void add(String s) {
list.add(s);
}
public void clear() {
list.clear();
}
}
There is no error in the code. App runs successfully. But images are not loading.
final String POSTER_BASE_URL = " http://image.tmdb.org/t/p/";
The space at the beginning of the string was the issue. Picasso will try and load url with space at front.
So String.trim() will remove the space from the beginning as well as the end of a String.
Picasso.with(mContext).load(POSTER_FINAL_URL.trim()).into(moviePoster)
I'm working on an app and I'm trying to show a listview filled with information from a MySQL database. I already have a different activity where I send and receive from the database using php, I'm doing something similar. I'm not sure if the error I'm having is something with the adapter class or from the Json Parsing part in the AsyncTask. These are the files:
package com.example.xxx.xxx;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
public class ListActivity extends ActionBarActivity {
ListView list;
ArrayList<Places> placeslist;
PlacesAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_row);
placeslist = new ArrayList<Places>();
new JASONTask().execute("http://xxx.xxx.com/getlist.php");
adapter = new PlacesAdapter(getApplicationContext(), R.layout.single_row, placeslist);
list = (ListView)findViewById(R.id.listView);
list.setAdapter(adapter);
}
public class JASONTask extends AsyncTask<String,Void,Boolean>{
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(ListActivity.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line ="";
while ((line = reader.readLine()) != null){
buffer.append(line);
}
String finalJson = buffer.toString();
JSONArray theJson = new JSONArray(finalJson);
for (int i=0; i<theJson.length(); i++){
Places place = new Places();
JSONObject jRealObject = theJson.getJSONObject(i);
place.setPlaces_id(jRealObject.getString("places_id"));
place.setName(jRealObject.getString("name"));
place.setLocation_address(jRealObject.getString("location_address"));
placeslist.add(place);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if(connection != null) {
connection.disconnect();
}
try {
if (reader != null){
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return true;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if (result == false){
//message not parsed
}
}
}
}
The Places class is:
package com.example.xxx.xxx;
/**
* Created by manhols on 10/12/2015.
*/
public class Places {
private String places_id;
private String name;
private String location_address;
public Places(){
}
public String getPlaces_id() {
return places_id;
}
public void setPlaces_id(String places_id) {
this.places_id = places_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLocation_address() {
return location_address;
}
public void setLocation_address(String location_address) {
this.location_address = location_address;
}
}
And the PlacesAdapter class is:
package com.example.xxx.xxx;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by manhols on 10/12/2015.
*/
public class PlacesAdapter extends ArrayAdapter<Places>{
ArrayList<Places> placeslist;
int Resource;
Context context;
LayoutInflater vi;
public PlacesAdapter(Context context, int resource, ArrayList<Places> objects) {
super(context, resource, objects);
Resource = resource;
placeslist = objects;
vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null){
vi.inflate(Resource, null);
convertView = vi.inflate(Resource,null);
holder = new ViewHolder();
holder.textView = (TextView)convertView.findViewById(R.id.textView);
holder.textView2 = (TextView)convertView.findViewById(R.id.textView2);
holder.textView5 = (TextView)convertView.findViewById(R.id.textView5);
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
holder.textView.setText(placeslist.get(position).getName());
holder.textView2.setText(placeslist.get(position).getPlaces_id());
holder.textView5.setText(placeslist.get(position).getLocation_address());
return convertView;
}
static class ViewHolder {
public TextView textView;
public TextView textView2;
public TextView textView5;
}
}
I will highly appreciate any help solving this issue.
I have spotted some errors in your adapter. Please inflate row as convertView = vi.inflate(Resource,parent,false); and also in parsing the data , return true only in try block. From your code i can see that even if you have an exception, you will be returning true which is wrong.
My problem was in the setContentView as #codeMagic mentioned before. I already solved this thanks to him
I have written a long code in android and which displays a progress dialog when the restaurant list is loaded into the listview. Now the problem is that its working fine when restaurant list is loaded again on users filter changes but only at the first time. it just keeps on displaying even if the listview is populated and user has to manually dismiss it pressing the back button of deivce. I dont knw where to write pg.dismiss() in this case. Posting my code here . plz advise me..
package com.Refinedymapps;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
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.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.location.Geocoder;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class Restaurantlist extends Activity implements OnClickListener, OnItemSelectedListener {
ProgressDialog pg;
private ImageButton imgbtn;
private ListView restaurant;
private TextView city;
String sendid,flagdopost="",linkurl;
LocationManager locationManger;
Geocoder gc;
Bundle bundle;
private int j=0;
private Spinner cuisine,area;
static ArrayList<HashMap<String,String>> customlist= new ArrayList<HashMap<String,String>>();
private String asynctaskflag="",cuisineval,areaval;
List<String> tempareanamelist,tempcuisinenamelist,areanamelist,cuisinelist,cuisineidlist,restaurantnames,areanames,restaurantidlist,originalcuisinelist,originalarealist;
String str,coun,stat,cid,sid,cityid,cityname;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.restaurantlisting);
linkurl=getResources().getString(R.string.linkurl);
city=(TextView)findViewById(R.id.textviewcity);
cuisine=(Spinner)findViewById(R.id.spncuisine);
area=(Spinner)findViewById(R.id.spnarea);
restaurant=(ListView)findViewById(R.id.lstrestaurant);
imgbtn=(ImageButton)findViewById(R.id.imageButton1);
bundle = this.getIntent().getExtras();
imgbtn.setImageResource(R.drawable.searchloc);
asynctaskflag="init";
new Thetask().execute(asynctaskflag,null,null);
imgbtn.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
Intent newlocintent=new Intent(Restaurantlist.this,Restaurantlistdisplay.class);
startActivity(newlocintent);
}
});
restaurant.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
Toast.makeText(getBaseContext(), "resname"+restaurantnames.get(arg2)+"areaname"+areanames.get(arg2), 10).show();
String[] getid={"itemclick",restaurantnames.get(arg2),areanames.get(arg2)};
new Thetask().execute(getid);
}
});
}
public void populateReslist()
{
Log.i("inside populatereslist","value of j is:"+j);
for(int i=0;i<restaurantnames.size();i++)
{
HashMap<String,String> temp = new HashMap<String,String>();
temp.put("Restaurant Name",restaurantnames.get(i).toString());
temp.put("Area Name", areanames.get(i).toString());
customlist.add(temp);
}
}
public List<String> getAreanames(String cityid)
{
String list = null;
areanamelist=new ArrayList<String>();
final HttpClient client=new DefaultHttpClient();
final HttpGet req=new HttpGet(linkurl+"/ymaws/resources/restaurant/"+cityid+"/areas/");
HttpResponse httpResponse;
try {
httpResponse=client.execute(req);
HttpEntity entity = httpResponse.getEntity();
Log.i("entity", entity.toString());
if (entity != null)
{
InputStream instream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
StringBuilder sb = new StringBuilder();
String line = null;
try
{
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
instream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
// Closing the input stream will trigger connection release
list= sb.toString();
Log.i("areaname xml is", list.toString());
}
}
catch(Exception e)
{
}
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
try
{
DocumentBuilder builder = factory.newDocumentBuilder();
Document dom = builder.parse(new InputSource(new StringReader(list)));
Element root = dom.getDocumentElement();
NodeList items = root.getElementsByTagName("Area");
for (int i=0;i<items.getLength();i++)
{
Node item = items.item(i);
NodeList properties = item.getChildNodes();
for (int j=0;j<properties.getLength();j++)
{
Node property = properties.item(j);
String name = property.getNodeName();
if (name.equalsIgnoreCase("areaName"))
{
areanamelist.add(property.getFirstChild().getNodeValue());
}
else
{
}
}
}
//Log.i("areaname list in getAreas method", areanamelist.toString());
return areanamelist;
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
public List<String> getCuisines(String cityid)
{
String list = null;
cuisinelist=new ArrayList<String>();
cuisineidlist=new ArrayList<String>();
final HttpClient client=new DefaultHttpClient();
final HttpGet req=new HttpGet(linkurl+"/ymaws/resources/restaurant/"+cityid+"/cuisines/");
HttpResponse httpResponse;
try {
httpResponse=client.execute(req);
HttpEntity entity = httpResponse.getEntity();
Log.i("entity", entity.toString());
if (entity != null)
{
InputStream instream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
StringBuilder sb = new StringBuilder();
String line = null;
try
{
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
instream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
// Closing the input stream will trigger connection release
list= sb.toString();
Log.i("cuisinename xml is", list.toString());
}
}
catch(Exception e)
{
}
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
try
{
DocumentBuilder builder = factory.newDocumentBuilder();
Document dom = builder.parse(new InputSource(new StringReader(list)));
Element root = dom.getDocumentElement();
NodeList items = root.getElementsByTagName("Cuisine");
for (int i=0;i<items.getLength();i++)
{
Node item = items.item(i);
NodeList properties = item.getChildNodes();
for (int j=0;j<properties.getLength();j++)
{
Node property = properties.item(j);
String name = property.getNodeName();
if (name.equalsIgnoreCase("cuisineName"))
{
cuisinelist.add(property.getFirstChild().getNodeValue());
}
else if(name.equalsIgnoreCase("cuisineId"))
{
cuisineidlist.add(property.getFirstChild().getNodeValue());
}
}
}
Log.i("getcuisine cuisinelist",cuisinelist.toString());
return cuisinelist;
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
public void firequery()
{
String url = null;
if(cuisineval=="*" && areaval=="*")
{
url=linkurl+"/ymaws/resources/restaurant/"+cityid+"/restaurants";
}
else if(cuisineval!="*" && areaval=="*")
{
for(int i=0;i<originalcuisinelist.size();i++)
{
Log.i("cuisinelist original item is",""+originalcuisinelist.get(i));
Log.i("cuisineidlist is",cuisineidlist.toString());
if((cuisine.getSelectedItem().toString()).equalsIgnoreCase(originalcuisinelist.get(i).toString()))
{
Log.i("cuisineid selected is",""+cuisineidlist.get(i));
url=linkurl+"/ymaws/resources/restaurant?cityid="+cityid+"&cuisineid="+cuisineidlist.get(i);
}
}
}
else if(cuisineval=="*" && areaval!="*")
{
url = linkurl+"/ymaws/resources/restaurant?cityid="+cityid+"&areanm="+area.getSelectedItem().toString();
}
else
{
for(int i=0;i<originalcuisinelist.size();i++)
{
if((cuisine.getSelectedItem().toString()).equalsIgnoreCase(originalcuisinelist.get(i).toString()))
{
url=linkurl+"/ymaws/resources/restaurant?cityid="+cityid+"&cuisineid="+cuisineidlist.get(i)+"&areanm="+area.getSelectedItem().toString();
}
}
}
getResult(url);
}
public void getResult(String url)
{
String list = null;
restaurantnames=new ArrayList<String> ();
areanames=new ArrayList<String>();
restaurantidlist=new ArrayList<String>();
final HttpClient client=new DefaultHttpClient();
Log.i("url is","url:"+url.toString());
final HttpGet req=new HttpGet(url.replaceAll(" ", "%20"));
HttpResponse httpResponse;
try {
httpResponse=client.execute(req);
HttpEntity entity = httpResponse.getEntity();
Log.i("entity", entity.toString());
if (entity != null)
{
InputStream instream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
StringBuilder sb = new StringBuilder();
String line = null;
try
{
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
instream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
list= sb.toString();
Log.i("list xml is", list.toString());
}
}
catch(Exception e)
{
}
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
try
{
if(list!=null)
{
DocumentBuilder builder = factory.newDocumentBuilder();
Document dom = builder.parse(new InputSource(new StringReader(list)));
Element root = dom.getDocumentElement();
NodeList items = root.getElementsByTagName("resLovData");
for (int i=0;i<items.getLength();i++)
{
Node item = items.item(i);
NodeList properties = item.getChildNodes();
for (int j=0;j<properties.getLength();j++)
{
Node property = properties.item(j);
String name = property.getNodeName();
if (name.equalsIgnoreCase("locName"))
{
restaurantnames.add(property.getFirstChild().getNodeValue());
}
else if(name.equalsIgnoreCase("areaName"))
{
areanames.add(property.getFirstChild().getNodeValue());
}
else if(name.equalsIgnoreCase("locId"))
{
restaurantidlist.add(property.getFirstChild().getNodeValue());
}
}
}
}
else
{
}
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
public class Thetask extends AsyncTask<String, Void, Void>
{
String x,y;
#Override
public void onPreExecute()
{
pg =new ProgressDialog(Restaurantlist.this);
pg.setMessage("fetching info....");
pg.setIndeterminate(true);
pg.setCancelable(true);
Log.i("inside preexecute","in pre execute");
pg.show();
}
public Void doInBackground(String... params)
{
if(params[0].equalsIgnoreCase("init"))
{
Log.i("inside doinbackground 1st",flagdopost);
cid=bundle.getString("cid");
sid=bundle.getString("sid");
cityid=bundle.getString("cityid");
cityname=bundle.getString("cityname");
originalcuisinelist=new ArrayList<String>();
originalcuisinelist=getCuisines(cityid);
tempcuisinenamelist = getCuisines(cityid);
tempcuisinenamelist.add(0,"All");
originalarealist=new ArrayList<String>();
originalarealist=getAreanames(cityid);
tempareanamelist=getAreanames(cityid);
tempareanamelist.add(0,"All");
Log.i("area are",tempareanamelist.toString());
flagdopost="init";
Log.i("inside doinbackground 1st",flagdopost);
}
else if(params[0].equalsIgnoreCase(""))
{
flagdopost="";
j++;
if(j!=1)
{
firequery();
flagdopost="itemselected";
Log.i("inside doinbackground 2nd",flagdopost);
}
}
else if(params[0].equalsIgnoreCase("itemclick"))
{
x=params[1];
y=params[2];
for(int i=0;i<restaurantidlist.size();i++)
{
if((params[1].toString()).equalsIgnoreCase(restaurantnames.get(i)))
{
sendid=restaurantidlist.get(i);
}
}
Log.i("in do in backgroung idforbundle is", sendid);
flagdopost="itemclicked";
}
return null;
}
public void onPostExecute(Void result)
{
if(flagdopost.equalsIgnoreCase("init"))
{
city.setText(cityname);
ArrayAdapter<String> adaptercuisine=new ArrayAdapter<String>(Restaurantlist.this,android.R.layout.simple_spinner_item,tempcuisinenamelist);
adaptercuisine.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
ArrayAdapter<String> adapterarea=new ArrayAdapter<String>(Restaurantlist.this,android.R.layout.simple_spinner_item,tempareanamelist);
adapterarea.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
area.setAdapter(adapterarea);
area.setSelection(0);
cuisine.setAdapter(adaptercuisine);
cuisine.setSelection(0);
area.setOnItemSelectedListener(Restaurantlist.this);
cuisine.setOnItemSelectedListener(Restaurantlist.this);
}
else if(flagdopost.equalsIgnoreCase("itemselected"))
{
customlist.clear();
populateReslist();
restaurant.invalidateViews();
restaurant.setAdapter(new SimpleAdapter(Restaurantlist.this,customlist,R.layout.customlistrow,new String[] {"Restaurant Name","Area Name"},
new int[] {R.id.tvresname,R.id.tvareaname})
{
#Override
public View getView(int position, View convertView,ViewGroup parent)
{
View view =super.getView(position, convertView, parent);
return view;
}
});
}
else if(flagdopost.equalsIgnoreCase("itemclicked"))
{
Bundle bundle=new Bundle();
bundle.putString("locid",sendid);
Toast.makeText(getBaseContext(), "locId in dopost new one"+sendid, 10).show();
Intent resdetail = new Intent(Restaurantlist.this,Restaurantdetail.class);
resdetail.putExtras(bundle);
startActivity(resdetail);
}
pg.dismiss();
}
}
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3)
{
switch(arg0.getId())
{
case R.id.spncuisine:
asynctaskflag="";
if(cuisine.getSelectedItem().toString()!="All")
{
cuisineval=cuisine.getSelectedItem().toString();
}
else
{
cuisineval="*";
}
new Thetask().execute(asynctaskflag,null,null);
break;
case R.id.spnarea:
asynctaskflag="";
if(area.getSelectedItem().toString()!="All")
{
areaval=area.getSelectedItem().toString();
}
else
{
areaval="*";
}
new Thetask().execute(asynctaskflag,null,null);
break;
}
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
Try declaring your ProgressDialog inside the AsyncTask. Instead of as a Activity member variable.
public class Thetask extends AsyncTask<String, Void, Void>
{
ProgressDialog pg = null;
String x,y;
#Override
public void onPreExecute()
...
I am trying to read an RSS feed. I have tried many links using the code below and succeeded, but when I try with that link above I get a FileNotFoundException. What could cause this, and how do I fix my code?
EfficientAdapter class:
package com.xmlparse;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class EfficientAdapter extends BaseAdapter
{
private Activity activity;
private ArrayList<Post> data;
private static LayoutInflater inflater = null;
//public ImageLoader imageLoader;
ViewHolder holder;
EfficientAdapter(Activity a, ArrayList<Post> d) {
activity = a;
data = d;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// imageLoader = new ImageLoader(activity.getApplicationContext());
}
#Override
public int getCount() {
return data.toArray().length;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
public static class ViewHolder {
public TextView label;
public TextView addr;
public ImageView image;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null) {
vi = inflater.inflate(R.layout.row, null);
holder = new ViewHolder();
holder.label = (TextView) vi.findViewById(R.id.title);
holder.addr = (TextView) vi.findViewById(R.id.details);
holder.image = (ImageView) vi.findViewById(R.id.thumb);
vi.setTag(holder);
} else
holder = (ViewHolder) vi.getTag();
holder.label.setText(data.get(position).getTitle());
// holder.addr.setText(data.get(position).getPubDate());
holder.addr.setText(data.get(position).getDescription());
imageLoader.DisplayImage((data.get(position).getThumbnail()), activity,
holder.image, 72, 72);
URL url = null;
try {
url = new URL((data.get(position).getThumbnail()));
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InputStream content = null;
try {
content = (InputStream)url.getContent();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Drawable d = Drawable.createFromStream(content , "src");
Bitmap mIcon1 = null;
try {
mIcon1 =
BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
holder.image.setImageBitmap(Bitmap.createScaledBitmap(mIcon1, 72, 72, false));
return vi;
}
}
Post class:
package com.xmlparse;
public class Post {
private String title;
private String thumbnail;
private String url;
private String description;
private String pubDate;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getThumbnail() {
return thumbnail;
}
public void setThumbnail(String thumbnail) {
this.thumbnail = thumbnail;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public void setDescription(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
public void setPubDate(String pubDate) {
this.pubDate = pubDate;
}
public String getPubDate() {
return pubDate;
}
}
xmlparsemain activity class:
package com.xmlparse;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
public class xmlparsemain extends Activity {
/** Called when the activity is first created. */
ListView lv1;
ProgressDialog ShowProgress;
public ArrayList<Post> PostList = new ArrayList<Post>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lv1 = (ListView) findViewById(R.id.listView1);
ShowProgress = ProgressDialog.show(xmlparsemain.this, "",
"Loading. Please wait...", true);
new loadingTask().execute("http://screenrant.com/mobile/movie-reviews-feed.php");
lv1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(Intent.ACTION_VIEW).setData(Uri
.parse(PostList.get(position).getUrl()));
startActivity(intent);
}
});
}
class loadingTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... urls) {
SAXHelper sh = null;
try {
sh = new SAXHelper(urls[0]);
} catch (MalformedURLException e) {
e.printStackTrace();
}
sh.parseContent("");
return "";
}
protected void onPostExecute(String s) {
lv1.setAdapter(new EfficientAdapter(xmlparsemain.this, PostList));
ShowProgress.dismiss();
}
}
class SAXHelper {
public HashMap<String, String> userList = new HashMap<String, String>();
private URL url2;
public SAXHelper(String url1) throws MalformedURLException {
this.url2 = new URL(url1);
}
public RSSHandler parseContent(String parseContent) {
RSSHandler df = new RSSHandler();
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
xr.setContentHandler(df);
/* URLConnection con = url2.openConnection();
con.setConnectTimeout(20000);
InputSource is = new InputSource(new InputStreamReader(con.getInputStream()));
xr.parse(is);*/
xr.parse(new InputSource(url2.openStream()));
} catch (Exception e) {
e.printStackTrace();
}
return df;
}
}
class RSSHandler extends DefaultHandler {
private Post currentPost = new Post();
StringBuffer chars = new StringBuffer();
#Override
public void startElement(String uri, String localName, String qName,
Attributes atts) {
chars = new StringBuffer();
if (localName.equalsIgnoreCase("item")) {
}
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (localName.equalsIgnoreCase("title")
&& currentPost.getTitle() == null) {
currentPost.setTitle(chars.toString());
}
if (localName.equalsIgnoreCase("pubDate")
&& currentPost.getPubDate() == null) {
currentPost.setPubDate(chars.toString());
}
if (localName.equalsIgnoreCase("description")
&& currentPost.getDescription() == null) {
currentPost.setDescription(chars.toString());
}
if (localName.equalsIgnoreCase("thumbnail")
&& currentPost.getThumbnail() == null) {
currentPost.setThumbnail(chars.toString());
}
if (localName.equalsIgnoreCase("link")
&& currentPost.getUrl() == null) {
currentPost.setUrl(chars.toString());
}
if (localName.equalsIgnoreCase("item")) {
PostList.add(currentPost);
currentPost = new Post();
}
}
#Override
public void characters(char ch[], int start, int length) {
chars.append(new String(ch, start, length));
}
}
}
My logcat report:
02-29 15:20:44.183: W/System.err(2470): java.io.FileNotFoundException: http://screenrant.com/mobile/movie-news-feed.php
try using HTtpConnection instead of URLConnection, as follows:
InputStream callWebErvice(String serviceURL){
// http get client
HttpClient client=new DefaultHttpClient();
HttpGet getRequest=new HttpGet();
try {
// construct a URI object
getRequest.setURI(new URI(serviceURL));
} catch (URISyntaxException e) {
Log.e("URISyntaxException", e.toString());
}
// buffer reader to read the response
BufferedReader in=null;
// the service response
HttpResponse response=null;
try {
// execute the request
response = client.execute(getRequest);
} catch (ClientProtocolException e) {
Log.e("ClientProtocolException", e.toString());
} catch (IOException e) {
Log.e("IO exception", e.toString());
}
if(response!=null)
return response.getEntity().getContent();
else
return null;
}
and change line xr.parse(new InputSource(url2.openStream()));
to
xr.parse(new InputSource(callWebErvice(url2)));