Android - Null pointer on setAdapter function - android

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

Related

Making an app that recieves Json data from tmdb.org

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];

When I tap the refresh button the images never appear

I have been trying too hard to get around this problom, when I tap the refresh button in my app, the images doesn't load on the screen.
This the DataFragment file, when i build this app there are no errors.
package com.example.popularmovis;
import android.app.Fragment;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
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.GridView;
import android.os.AsyncTask;
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.jar.JarException;
/**
* A placeholder fragment containing a simple view.
*/
public class DataFragment extends Fragment {
public ImageAdapter display;
public DataFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Add this line in order for this fragment to handle menu events.
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.datafragment_menu, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_refresh) {
FetchMovieData movieData = new FetchMovieData();
movieData.execute();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
display = new ImageAdapter(rootView.getContext());
GridView gridView = (GridView) rootView.findViewById(R.id.gridView_movies);
gridView.setAdapter(display); // uses the view to get the context instead of getActivity().
return rootView;
}
public class FetchMovieData extends AsyncTask<Void, Void, String[]>{
private final String LOG_TAG = FetchMovieData.class.getSimpleName();
private String[] extractdisplayFromJason(String jasnData)
throws JSONException{
//These jason display need to be extracted
final String movie_results = "results";
final String movie_poster = "poster_path";
JSONObject movieData = new JSONObject(jasnData);
JSONArray movieArray = movieData.getJSONArray(movie_results);
String[] posterAddreess = new String[movieArray.length()];
//Fill ther posterAddreess with the URL to display
for(int j=0; j < movieArray.length(); j++){
String posterPath;
JSONObject movieArrayItem = movieArray.getJSONObject(j);
posterPath = movieArrayItem.getString(movie_poster);
posterAddreess[j] = "http://image.tmdb.org/t/p/w185/" + posterPath;
}
for (String s : posterAddreess) {
Log.v(LOG_TAG, "Thumbnail Links: " + s);
}
return posterAddreess;
}
#Override
protected String[] doInBackground(Void... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String JsonData = null;
String country = "US";
String rating = "R";
String sort = "popularity.desc";
String apiKey = "";
//building the URL for the movie DB
try {
//building the URL for the movie DB
final String MovieDatabaseUrl = "https://api.themoviedb.org/3/discover/movie?";
final String Country_for_release = "certification_country";
final String Rating = "certification";
final String Sorting_Order = "sort_by";
final String Api_Id = "api_key";
Uri buildUri = Uri.parse(MovieDatabaseUrl).buildUpon()
.appendQueryParameter(Country_for_release, country)
.appendQueryParameter(Rating, rating)
.appendQueryParameter(Sorting_Order, sort)
.appendQueryParameter(Api_Id, apiKey)
.build();
//Converting URI to URL
URL url = new URL(buildUri.toString());
Log.v(LOG_TAG, "Built URI = "+ buildUri.toString());
//Create the request to the Movie Database
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
//Read the input from the database into string
InputStream inputStream = urlConnection.getInputStream();
//StringBuffer for string Manipulation
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) {
// 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 + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
JsonData = buffer.toString();
Log.v(LOG_TAG,"Forecaast Jason String" + JsonData );
} catch (IOException e) {
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
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 extractdisplayFromJason(JsonData);
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
}
return null;
}
protected void onPostExecute(String[] posterAddreess) {
for (String poster : posterAddreess) {
display.addItem(poster);
}
}
}
}
This the ImageAdapter code
package com.example.popularmovis;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import com.example.popularmovis.R;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ArrayList<String> images = new ArrayList<String>();
public ImageAdapter(Context c){
mContext = c;
}
#Override
public int getCount(){
return images.size();
}
#Override
public Object getItem(int position){
return images.get(position);
}
public long getItemId(int position){
return 0;
}
public View getView(int position, View convertView, ViewGroup parent){
ImageView imageview;
if (convertView == null){
imageview = new ImageView(mContext);
imageview.setPadding(0, 0, 0, 0);
//imageview.setLayoutParams(new GridLayout.MarginLayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
imageview.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageview.setAdjustViewBounds(true);
} else {
imageview = (ImageView) convertView;
}
Picasso.with(mContext).load(images.get(position)).placeholder(R.mipmap.ic_launcher).into(imageview);
return imageview;
}
/*
Custom methods
*/
public void addItem(String url){
images.add(url);
}
public void clearItems() {
images.clear();
}
}
When you use this in your onCreate method like this, it means that the object is local to the method and can't be use in other methods.
ImageAdapter display = new ImageAdapter(rootView.getContext());
First create a global class member variable
private ImageAdapter display;
then inside your onCreate method do this
display = new ImageAdapter(rootView.getContext());

Images are not loading in GridView using picasso 2.5.2

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)

Reading xml from rss feed

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. :)

FileNotFoundException while reading RSS in Android

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)));

Categories

Resources