I'm designing a listview that displays food information list from php server.
the url I passed is a php file after I convert it to json file. the list is not shown and whent I press refresh from menu I keep getting
(app stopped working) ..
here is FoodView.java Activity
import android.content.Context;
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import alsaad.layla.mysqldemo.Models.FoodModel;
import static android.R.attr.resource;
import static android.content.Context.LAYOUT_INFLATER_SERVICE;
public class FoodView extends AppCompatActivity {
private ListView lvFood;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_food_view);
lvFood = (ListView) findViewById(R.id.lvFood);
}
public class JSONTask extends AsyncTask<String, String, List<FoodModel>> {
#Override
protected List<FoodModel> doInBackground(String... params) {
HttpURLConnection httpURLConnection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
InputStream inputStream = httpURLConnection.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONArray parentArray = new JSONArray(finalJson);
List<FoodModel> foodModelList = new ArrayList<>();
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
FoodModel foodModel = new FoodModel();
foodModel.setFood(finalObject.getString("name"));
//foodModel.setStatus(finalObject.getString("status"));
foodModel.setAmount(finalObject.getInt("amount"));
foodModel.setDescription(finalObject.getString("description"));
foodModel.setDate(finalObject.getInt("exDate"));
foodModelList.add(foodModel);
}
return foodModelList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(List<FoodModel> result) {
super.onPostExecute(result);
FoodAdapter adapter = new FoodAdapter(getApplicationContext(), R.layout.row, result);
lvFood.setAdapter(adapter);
}}
public class FoodAdapter extends ArrayAdapter {
private List<FoodModel> foodModelList;
private int resource;
private LayoutInflater inflater;
public FoodAdapter(Context context, int resource, List<FoodModel> objects) {
super(context, resource, objects);
foodModelList = objects;
this.resource = resource;
inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(resource, null);
}
ImageView ivIcon;
TextView foodName, txt_amount, txt_desc, txt_date, txt_status;
ivIcon = (ImageView) convertView.findViewById(R.id.ivIcon);
foodName = (TextView) convertView.findViewById(R.id.foodName);
txt_amount = (TextView) convertView.findViewById(R.id.txt_amount);
txt_desc = (TextView) convertView.findViewById(R.id.txt_desc);
// txt_status = (TextView) convertView.findViewById(R.id.txt_status);
txt_date = (TextView) convertView.findViewById(R.id.txt_date);
foodName.setText(foodModelList.get(position).getFood());
txt_amount.setText("Amount: " + foodModelList.get(position).getAmount());
txt_desc.setText(foodModelList.get(position).getDescription());
// txt_status.setText(foodModelList.get(position).getStatus());
txt_date.setText("Date: " + foodModelList.get(position).getDate());
return convertView;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.navigation_drawer, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_refresh) {
new JSONTask().execute("http://10.0.3.2/MySqlDemo/food.php");
return true;
}
return super.onOptionsItemSelected(item);
}
}
FoodModel.java
public class FoodModel {
private String food;
//private enum status;
private int amount;
private String image;
private String description;
private int date;
public int getDate() {
return date;
}
public void setDate(int date) {
this.date = date;
}
public String getFood() {
return food;
}
public void setFood(String food) {
this.food = food;
}
//public String getStatus() {
// return status;
// }
// public void setStatus(String status) {
// this.status = status;
//}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
}
the logcat error:
02-20 05:06:08.084 4514-4514/alsaad.layla.mysqldemo E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:330)
at android.widget.ListView.setAdapter(ListView.java:462)
at alsaad.layla.mysqldemo.FoodView$JSONTask.onPostExecute(FoodView.java:128)
at alsaad.layla.mysqldemo.FoodView$JSONTask.onPostExecute(FoodView.java:54)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
It seems like you are getting an exception in your for loop that's why it goes into an exception and returns null, so it shows a null pointer exception. Please replace getString() with optSting() and getInt() with optInt().
Solution:- Please put break point in your for loop and find it out otherwise use below option.
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
FoodModel foodModel = new FoodModel();
foodModel.setFood(finalObject.optString("name"));
//foodModel.setStatus(finalObject.optString("status"));
foodModel.setAmount(finalObject.optInt("amount"));
foodModel.setDescription(finalObject.optString("description"));
foodModel.setDate(finalObject.optInt("exDate"));
foodModelList.add(foodModel);
}
return null; replace with return new ArrayList<>(); to get from crash.
The method getCount() within the ArrayAdater returns the lenght of the object list atached to the adapter:
/**
* {#inheritDoc}
*/
public int getCount() {
return mObjects.size();
}
As you are using a custom ArrayAdapter i think you must Override this function to make it returns the size of your own objects list:
public int getCount() {
return foodModelList.size();
}
Why are you using ArrayAdapter instead i would suggest you to use BaseAdapter
It is the issue when you object is not able to get instance of ArrayAdpter and hence returning null pointer exception at getCount()
Related
I've been learning Java for a few months. Nowadays I'm creating an app which downloads web content and shows the data in a ListView. The problem is that everything takes a very long time - about 25 second from the launch of the app to fill the list with elements. What is more, there is no difference between it running on a real device or an Android emulator.
In my opinion, the Java code is not bad because most of it is from my course on Udemy.
How can I improve this? Where is the problem?
Reports from logcat and AVD setting [ss]:
Here's my code below:
MainActivity.java
package com.example.user.legionisciapp;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MainActivity extends AppCompatActivity {
ListView listView;
List<News> newsList = new ArrayList<>();
ArrayList<String> titles = new ArrayList<>();
ArrayList<String> desc = new ArrayList<>();
ArrayList<String> urls = new ArrayList<>();
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... strings) {
URL url;
HttpURLConnection connection = null;
String result = "";
try {
url = new URL(strings[0]);
connection = (HttpURLConnection) url.openConnection();
InputStream inputStream = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (Exception e) {
e.printStackTrace();
return "Failed";
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DownloadTask downloadTask = new DownloadTask();
try {
String result = downloadTask.execute("https://www.legionisci.com").get();
String[] resultSplit = result.split("<div id=\"mecze\">");
result = resultSplit[0];
resultSplit = result.split("<div id=\"listanewsow\">");
result = resultSplit[1];
Pattern p = Pattern.compile("class=\"b\" title=\"(.*?)\">");
Matcher m = p.matcher(result);
while (m.find()) {
titles.add(m.group(1));
}
p = Pattern.compile("></a>(.*?)</div>");
m = p.matcher(result);
while (m.find()) {
desc.add(m.group(1));
}
p = Pattern.compile("alt=\"\" class=\"zl\" /></a>(.*?)<");
m = p.matcher(result);
while (m.find()) {
urls.add("https://www.legionisci.com" + m.group(1));
}
} catch (Exception e) {
e.printStackTrace();
}
listView = findViewById(R.id.listView);
for (int i = 0; i < 4; i++) {
newsList.add(new News(R.drawable.ll, titles.get(i), desc.get(i)));
NewsListAdapter newsListAdapter = new NewsListAdapter(this, R.layout.news_list, newsList);
listView.setAdapter(newsListAdapter);
}
}
}
News.java
package com.example.user.legionisciapp;
public class News {
int image;
String title, desc;
public News(int image, String title, String desc) {
this.image = image;
this.title = title;
this.desc = desc;
}
public int getImage() {
return image;
}
public String getTitle() {
return title;
}
public String getDesc() {
return desc;
}
}
NewsListAdapter.class
package com.example.user.legionisciapp;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
public class NewsListAdapter extends ArrayAdapter<News> {
Context ctx;
int resource;
List<News> newsList;
public NewsListAdapter (Context ctx, int resource, List<News> newsList){
super(ctx, resource, newsList);
this.ctx = ctx;
this.resource = resource;
this.newsList = newsList;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(ctx);
View view = inflater.inflate(R.layout.news_list, null);
TextView title = view.findViewById(R.id.tvTitle);
TextView desc = view.findViewById(R.id.tvDesc);
ImageView image = view.findViewById(R.id.thumb);
News news = newsList.get(position);
title.setText(news.getTitle());
desc.setText(news.getDesc());
image.setImageDrawable(ctx.getResources().getDrawable(news.getImage()));
return view;
}
}
You can't do something like this:
String result = downloadTask.execute("https://www.legionisci.com").get();
That is not the right way to use an AsyncTask! The problem is that the async task is executed in a background thread but if you do .get() the main thread is paused until the async task finishes his job. So this is the reason of the long wait at startup.
What you have to do is:
Starting the task this way
downloadTask.execute("https://www.legionisci.com");
Using the onPostExecute(String result) method (executed on the main thread) to get the result and update the UI .
More on this:
https://developer.android.com/reference/android/os/AsyncTask
I am planning to make a news app. I have created a simple search view inside the action bar of my app.
This is the Main activity
package com.example.hp.simplenews;
import android.app.Activity;
import android.app.LoaderManager;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.content.Loader;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SearchView;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<List<News>> {
private int Newsloaderid = 1;
private Newsadapter newslistadapter;
private String search_query_input = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView newslistview = findViewById(R.id.list);
newslistadapter = new Newsadapter(this, new ArrayList<News>());
newslistview.setAdapter(newslistadapter);
LoaderManager loaderManager = getLoaderManager();
loaderManager.initLoader(Newsloaderid, null, MainActivity.this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the options menu from XML
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options_menu, menu);
// Get the SearchView and set the searchable configuration
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();
// Assumes current activity is the searchable activity
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false); // Do not iconify the widget; expand it by default
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String newtext) {
search_query_input = newtext;
return true;
}
#Override
public boolean onQueryTextChange(String query) {
return true;
}
});
return true;
}
#Override
public Loader<List<News>> onCreateLoader(int i, Bundle bundle) {
return new NewsLoader(this, search_query_input);
}
#Override
public void onLoadFinished(Loader<List<News>> loader, List<News> news) {
newslistadapter.clear();
if (news != null && !news.isEmpty()) {
newslistadapter.addAll(news);
}
}
#Override
public void onLoaderReset(Loader loader) {
newslistadapter.clear();
}
}
The SearchResultsActivity handles the HTTP request and JSON parsing.
This is the SearchResultsActivity
package com.example.hp.simplenews;
import android.app.Activity;
import android.app.LoaderManager;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.content.Loader;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.widget.SearchView;
import android.widget.TextView;
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.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
public class SearchResultsActivity extends Activity{
String query_string = "";
private static final String LOG_TAG = SearchResultsActivity.class.getName();
public static URL createUrl(String query_url) throws MalformedURLException {
URL url = null;
String APIKey = "apiKey";
String query = "q";
try {
final String base_url = "https://newsapi.org/v2/everything?";
Uri final_url = Uri.parse(base_url).buildUpon()
.appendQueryParameter(query, query_url)
.appendQueryParameter(APIKey, "48f67c1e66994aa8a92f92a48b5f6581")
.build();
url = new URL(final_url.toString());
Log.i(LOG_TAG, "THE FINAL URL IS" + final_url);
} catch (MalformedURLException e) {
e.printStackTrace();
Log.e(LOG_TAG, "the url couldn't be made");
}
return url;
}
private static final String HTTPREQUEST(URL url) throws IOException {
String jsonresponse = "";
if (jsonresponse == null) {
return null;
}
HttpURLConnection httpURLConnection = null;
InputStream inputStream = null;
try {
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setReadTimeout(10000);
httpURLConnection.setConnectTimeout(150000);
httpURLConnection.connect();
if (httpURLConnection.getResponseCode() == 200) {
inputStream = httpURLConnection.getInputStream();
jsonresponse = readfromstream(inputStream);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
inputStream.close();
}
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
return jsonresponse;
}
private static final String readfromstream(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String urlline = bufferedReader.readLine();
while (urlline != null) {
output.append(urlline);
urlline = bufferedReader.readLine();
}
return output.toString();
}
private static List<News> JSONParser(String NewsJSON) throws JSONException {
if (TextUtils.isEmpty(NewsJSON)) {
return null;
}
List<News> news = new ArrayList<>();
try {
JSONObject basejson = new JSONObject(NewsJSON);
JSONArray articles = basejson.getJSONArray("articles");
for (int i = 0; i < articles.length(); i++) {
News newss = new News();
JSONObject c = articles.getJSONObject(i);
JSONObject source = c.getJSONObject("source");
newss.setMsource(source.getString("name"));
newss.setMtitle(c.getString("title"));
newss.setMdescription(c.getString("description"));
newss.setMtime(c.getString("publishedAt"));
String image = c.getString("urlToImage");
if (image != null) {
newss.setmImage(c.getString("urlToImage"));
}
newss.setNewsURL(c.getString("url"));
news.add(newss);
}
} catch (JSONException j) {
Log.e(LOG_TAG, "couldn't parse jSON");
}
return news;
}
public static List<News> fetchnews(String search_query) throws IOException, JSONException {
URL url = createUrl(search_query);
String JSONRESPONSE = null;
try {
JSONRESPONSE = HTTPREQUEST(url);
} catch (IOException j) {
j.printStackTrace();
}
List<News> news = JSONParser(JSONRESPONSE);
return news;
}
#Override
protected void onNewIntent(Intent intent) {
setIntent(intent);
try {
handleIntent(intent);
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
private void handleIntent(Intent intent) throws MalformedURLException {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
query_string = intent.getStringExtra(SearchManager.QUERY);
Log.i(LOG_TAG, "The querytext is" + query_string);
}
}
}
This whole process of refreshing the list view is done by a AsyncTaskLoader
The custom Asyntaskloader class is copied below:
public class NewsLoader extends AsyncTaskLoader<List<News>> {
private String mUrl;
private static String LOG_TAG = NewsLoader.class.getName();
public NewsLoader(Context context, String url) {
super(context);
mUrl = url;
}
#Override
protected void onStartLoading() {
forceLoad();
}
#Override
public List<News> loadInBackground() {
if (mUrl == null) {
return null;
}
List<News> news = null;
try {
news = SearchResultsActivity.fetchnews(mUrl);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return news;
}
}
Now I have the search query entered by the user stored in the search_query_input variable in the MainActivity.
But the app just gets stuck when I press the submit button. The override methods for the asynctaskloader are not getting executed at all.
What is happening? Any help will be much appreciated.
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener(){
onQueryTextChange(String newText){
//when user type in searchview get string as newText parameter
asynTaskMethod(newText);
}
onQueryTextSubmit(String query){
//when user press submit button in searchview get string as query parameter
asynTaskMethod(query);
}
});
I have would like to rewrite my method so that it returns a List of Movie class rather than a list of String class, here's the method I want to change:
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;
}
I tried to rewrite it like this:
private List<Movie> getMovieDataFromJson(String forecastJsonStr)
throws JSONException {
JSONObject movieJson = new JSONObject(forecastJsonStr);
JSONArray movieArray = movieJson.getJSONArray("results");
List<Movie> movies = new ArrayList<>();
for (int i = 0; i < movieArray.length(); i++) {
JSONObject movie = movieArray.getJSONObject(i);
Movie movie1 = new Movie(movie.getString("original_title"), movie.getDouble("vote_average"), movie.getString("release_date"), movie.getString("overview"), movie.getString("poster_path"));
movies.add(movie1);
}
return movies;
}
But the problem is I'm getting error on line 139, it's saying required is String but found Movie instead. Here is line 139:
return getMovieDataFromJson(movieJsonStr);
Here is my code:
package com.projmobileapp.pmdbadd.pmdb;
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 MainActivityFragment extends Fragment {
//ArrayAdapter<String> mMovieAdapter;
//String[] movieId,movieTitle,movieOverview,movieReleaseDate,movieVoteAverage;
String[] moviePosterPath = new String[0];
public MainActivityFragment() {
}
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_movie);
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.mainactivityfragment, 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=INSERTAPIKEY");
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();
}
}
}
The problem here is that your AsyncTask defines the result type for doInBackground() as List<String>. You need to change the line:
class FetchMovieTask extends AsyncTask<Void, Void, List<String>>
to
class FetchMovieTask extends AsyncTask<Void, Void, List<Movie>>
and change doInBackground() to return List<Movie>
Im trying to add the name of the resturaunt and the category onto a card view via custom adapter. How ever when ever i run the program i keep getting a java null pointer exception. Im a little bit startled by this, i have been looking through the web but have found no luck. Thanks in advance!
//Main:
package com.example.rifatrashid.compass;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
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.apache.http.util.ByteArrayBuffer;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Rifat Rashid on 2/23/2015.
*/
public class chooseactivity extends ActionBarActivity{
private ListView listView1;
ArrayList<Places> venuesList;
final String GOOGLE_KEY = "AIzaSyD72cNSZ6PoMFwvDe-ihUDNcTrAnuMynuE";
TextView t1;
final String latitude = "40.7463956";
final String longitude = "-73.9852992";
PlacesAdapter adapter1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chooselocation);
new googleplaces().execute();
/*Places place_data[] = new Places[]{
new Places("Lunch", "Mandarin Cuisine"),
new Places("Brunch", "Fredmeyer"),
new Places("Supplies", "Target")
};
*/
/*
PlacesAdapter adapter = new PlacesAdapter(this, R.layout.listview_item_row, place_data);
listView1 = (ListView) findViewById(R.id.listView);
listView1.setAdapter(adapter);
*/
}
class googleplaces extends AsyncTask<View, Void, String> { //Line54
String temp;
#Override
protected String doInBackground(View... urls) {
temp = makeCall("https://maps.googleapis.com/maps/api/place/search/json?location=" + latitude + "," + longitude + "&radius=100&sensor=true&key=" + GOOGLE_KEY);
return "";
}
#Override
protected void onPreExecute() {}
#Override
protected void onPostExecute(String result) {
if (temp == null) {
//Error coce exception
} else {
venuesList = (ArrayList<Places>) parseGoogleParse(temp);
List<String> listTitle = new ArrayList<>();
//List<Places> gPlace = new ArrayList<>();
Places[] place_data = new Places[100];
for (int i = 0; i < venuesList.size(); i++) {
//listTitle.add(i, venuesList.get(i).getName() + "\nOpen Now: " + venuesList.get(i).getOpenNow() + "\n(" + venuesList.get(i).getCategory() + ")");
new Places(venuesList.get(i).getCategory().toString(), venuesList.get(i).getName().toString()); //Line77
//gPlace.add(new Places(venuesList.get(i).getCategory(), "y"));
}
adapter1 = new PlacesAdapter(chooseactivity.this, R.layout.listview_item_row, place_data);
listView1 = (ListView) findViewById(R.id.listView);
listView1.setAdapter(adapter1);
}
}
}
public static String makeCall(String url) {
// string buffers the url
StringBuffer buffer_string = new StringBuffer(url);
String replyString = "";
// instanciate an HttpClient
HttpClient httpclient = new DefaultHttpClient();
// instanciate an HttpGet
HttpGet httpget = new HttpGet(buffer_string.toString());
try {
// get the responce of the httpclient execution of the url
HttpResponse response = httpclient.execute(httpget);
InputStream is = response.getEntity().getContent();
// buffer input stream the result
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(20);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
// the result as a string is ready for parsing
replyString = new String(baf.toByteArray());
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(replyString);
// trim the whitespaces
return replyString.trim();
}
private static ArrayList<Places> parseGoogleParse(final String response) {
ArrayList<Places> temp = new ArrayList<>();
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.has("results")) {
JSONArray jsonArray = jsonObject.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
Places poi = new Places();
if (jsonArray.getJSONObject(i).has("name")) {
poi.setName(jsonArray.getJSONObject(i).optString("name"));
poi.setRating(jsonArray.getJSONObject(i).optString("rating", " "));
if (jsonArray.getJSONObject(i).has("opening_hours")) {
if (jsonArray.getJSONObject(i).getJSONObject("opening_hours").has("open_now")) {
if (jsonArray.getJSONObject(i).getJSONObject("opening_hours").getString("open_now").equals("true")) {
poi.setOpenNow("YES");
} else {
poi.setOpenNow("NO");
}
}
} else {
poi.setOpenNow("Not Known");
}
if (jsonArray.getJSONObject(i).has("types")) {
JSONArray typesArray = jsonArray.getJSONObject(i).getJSONArray("types");
for (int j = 0; j < typesArray.length(); j++) {
poi.setCategory(typesArray.getString(j) + ", " + poi.getCategory());
}
}
}
temp.add(poi);
}
}
} catch (Exception e) {
e.printStackTrace();
return new ArrayList<Places>();
}
return temp;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
}
Heres my Places Class:
package com.example.rifatrashid.compass;
/**
* Created by Rifat Rashid on 2/23/2015.
*/
public class Places {
public String category;
public String name;
public String rating;
public String open;
public Places(){
super();
}
public Places(String category, String name){
super();
this.category = "";
this.name = "";
this.rating = "";
this.open = "";
}
public String getCategory(){
return category;
}
public String getOpen(){
return open;
}
public String getName(){
return name;
}
public void setName(String name) {
this.name = name;
}
public void setRating(String rating) {
this.rating = rating;
}
public void setOpenNow(String openNow) {
this.open = openNow;
}
public void setCategory(String s) {
}
public String getOpenNow() {
return open;
}
}
My custom adapter class:
package com.example.rifatrashid.compass;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
/**
* Created by Rifat Rashid on 2/23/2015.
*/
public class PlacesAdapter extends ArrayAdapter<Places> {
Context context;
int layoutResourceId;
Places[] data;
//List<Places> data;
public PlacesAdapter(Context context, int layoutResourceId, Places[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
public View getView(int position, View convertView, ViewGroup parent){
View row = convertView;
PlacesHolder holder = null;
if(row == null){
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new PlacesHolder();
holder.titleTxt = (TextView) row.findViewById(R.id.placeTitle);
holder.sub = (TextView) row.findViewById(R.id.placeCategory);
row.setTag(holder);
}else{
holder = (PlacesHolder) row.getTag();
}
Places place = data[position];
holder.titleTxt.setText(place.getName());
holder.sub.setText(place.getCategory());
return row;
}
static class PlacesHolder{
TextView titleTxt, sub;
}
}
Error:
02-26 17:05:30.530 9757-9757/com.example.rifatrashid.compass E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.rifatrashid.compass, PID: 9757
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object reference
at com.example.rifatrashid.compass.chooseactivity$googleplaces.onPostExecute(chooseactivity.java:77)
at com.example.rifatrashid.compass.chooseactivity$googleplaces.onPostExecute(chooseactivity.java:54)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:898)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)
As your error log says, you have a problem with a line in your onPostExecute method in your googleplaces class of your chooseactivity activity. (Line 77)
Specifically, one of the elements that you're trying to call toString() on is null.
new Places(venuesList.get(i).getCategory().toString(), venuesList.get(i).getName().toString()); //Line77
To fix the error (but not necessarily your process), wrap this in an if statement that checks to see if the element is null. Like this, for example:
if (venuesList.get(i) != null && venuesList.get(i).getCategory() != null && venuesList.get(i).getName() != null) {
new Places(venuesList.get(i).getCategory().toString(), venuesList.get(i).getName().toString()); //Line77
}
Now this won't actually fix your code, just prevent this error from occurring. What you should really do is in Android Studio, put a breakpoint on Line 77 so that when you debug, you can see exactly which element is null and track back why that might be the case and how you can intercept it in the future.
I have an app I am trying to pass data through an ASYNC task but am getting a null pointer error in my onPosteExecute method. Seems like no matter how I change my code I still get this same fatal error:
10-31 18:43:56.517 1253-1253/com.brianstacks.project1 E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.brianstacks.project1, PID: 1253
java.lang.NullPointerException
at com.brianstacks.project1.MainActivity$MyTask.onPostExecute(MainActivity.java:277)
at com.brianstacks.project1.MainActivity$MyTask.onPostExecute(MainActivity.java:247)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Here is my code:
MainActivity.java
public class MainActivity extends ListActivity implements MasterFragment.OnListItemClickListener {
final String Tag = "Project 1 test";
EditText myEdit;
Button myButton;
ProgressBar pb;
SerialCustomObject myObject;
// create a reference to the list's needed for data
List<MyTask> tasks;
ArrayList<Places> placeList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if ((savedInstanceState != null)&& (savedInstanceState.getSerializable("name") != null)) {
Places name = (Places) savedInstanceState.getSerializable("name");
Log.v("name:",name.getName());
}
//initiate my tasks
tasks = new ArrayList<>();
pb = (ProgressBar)findViewById(R.id.progressBar);
myEdit = (EditText)findViewById(R.id.myEditText);
myButton = (Button)findViewById(R.id.myButton);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#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();
return id == R.id.action_settings || super.onOptionsItemSelected(item);
}
public void findAndRemoveFragment() {
FragmentManager mgr = getFragmentManager();
DetailFragment frag =
(DetailFragment) mgr.findFragmentByTag(DetailFragment.TAG);
if (frag == null) {
// No fragment found, possibly because the transaction
// hasn't completed yet.
} else {
// Fragment found. You can use it here.
FragmentTransaction trans = mgr.beginTransaction();
trans.remove(frag);
trans.commit();
// When the main thread runs, the fragment will be
// removed from the activity.
}
}
public void deviceStorage() {
// Read in a private file
try {
FileInputStream fis = this.openFileInput("some_file.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// Create new or open existing private file
try {
FileOutputStream fos = this.openFileOutput("some_other_file.txt", Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private void writeToFile(Context _c, String _filename, String _data) {
File external = _c.getExternalFilesDir(null);
File file = new File(external, _filename);
try {
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
if(myObject == null) {
myObject = new SerialCustomObject();
}
myObject.setData(_data);
oos.writeObject(myObject);
oos.close();
// Write bytes to the stream
fos.write(_data.getBytes());
// Close the stream to save the file.
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private String readFromFile(String _filename) {
File external = getExternalFilesDir(null);
File file = new File(external, _filename);
try {
FileInputStream fin = new FileInputStream(file);
InputStreamReader inReader = new InputStreamReader(fin);
BufferedReader reader = new BufferedReader(inReader);
// Reading data from our file using the reader
// and storing it our string buffer.
StringBuffer buffer = new StringBuffer();
String text = null;
// Make sure a line of text is available to be read.
while((text = reader.readLine()) != null) {
buffer.append(text + "\n");
}
// Close the reader and underlying stream.
reader.close();
// Convert the buffer to a string.
return buffer.toString();
} catch(IOException e) {
e.printStackTrace();
}
return null;
}
#Override
public void displayText(String myText) {
DetailFragment frag = (DetailFragment) getFragmentManager().findFragmentByTag(DetailFragment.TAG);
if (frag == null){
frag = DetailFragment.newInstance(myText);
getFragmentManager().beginTransaction()
.replace(R.id.container2,frag,DetailFragment.TAG)
.commit();
}else {
frag.setDisplayInfo(myText);
}
}
//#Override
public void onClick(View _v){
myEdit = (EditText)findViewById(R.id.myEditText);
String newString = myEdit.getText().toString();
Log.v(Tag,newString);
}
// the method for when the button is clicked
public void myClick(View _v){
// create a string to grab the text of the edit text
String myString = myEdit.getText().toString();
// replace the spaces with + to encode into the url
String encodedString = myString.replace(" ","+");
//check to see if online and if so continue to get the JSON data if not toast a message telling the user no connection
if (isOnline()){
requestData("https://maps.googleapis.com/maps/api/place/textsearch/json?query="+encodedString+"&key=AIzaSyB9iOw6wF4FwbOdUTZYiU_MxsbfWM5iMOI");
}else Toast.makeText(this, "Network isn't available", Toast.LENGTH_SHORT).show();
}
// method to get the data from ASYNC task
private void requestData(String uri) {
MyTask task = new MyTask();
task.execute(uri);
}
// method to check internet connectivity
protected boolean isOnline(){
ConnectivityManager cm =(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
protected void updateDisplay(ArrayList<Places> placeList){
// get instance of the Master List fragment then replaces container1 and commits it to the activity
MasterFragment frag = MasterFragment.newInstance(placeList);
getFragmentManager().beginTransaction()
.replace(R.id.container1, frag, MasterFragment.TAG).commit();
}
// Async task method to do network action in
private class MyTask extends AsyncTask<String ,String ,String>{
#Override
protected void onPreExecute() {
// add this to the task
tasks.add(this);
}
#Override
protected String doInBackground(String... params) {
return HttpManager.getData(params[0]);
}
#Override
protected void onPostExecute(String result) {
tasks.remove(this);
if(null != result && !result.isEmpty()) {
placeList = JSONParser.parseFeed(result);
updateDisplay(placeList);
}else {
Toast.makeText(MainActivity.this, "Can't connect to API", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onProgressUpdate(String... values) {
}
}
}
DetailFragment.java
package com.brianstacks.project1.fragments;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.brianstacks.project1.R;
/**
* Created by Brian Stacks
* on 10/27/14
* for FullSail.edu.
*/
public class DetailFragment extends Fragment {
public static final String TAG = "DetailFragment.TAG";
public static final String ARG_TAG = "DetailFragment.TAG";
public static DetailFragment newInstance(String myString) {
DetailFragment frag = new DetailFragment();
Bundle args = new Bundle();
args.putString(ARG_TAG, myString);
frag.setArguments(args);
return frag;
}
#Override
public View onCreateView(LayoutInflater _inflater, ViewGroup _container,
Bundle _savedInstanceState) {
// Create and return view for this fragment.
return _inflater.inflate(R.layout.detail_layout, _container, false);
}
#Override
public void onActivityCreated(Bundle _savedInstanceState) {
super.onActivityCreated(_savedInstanceState);
Bundle args = getArguments();
if(args != null && args.containsKey(ARG_TAG)){
setDisplayInfo(args.getString(ARG_TAG));
}
}
public void setDisplayInfo(String myText){
getArguments().putString(ARG_TAG,myText);
// Get our TextView and set some text to it.
TextView tv;
tv = (TextView)getView().findViewById(R.id.detailText);
tv.setText(myText);
}
}
MasterFragment.java
package com.brianstacks.project1.fragments;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListFragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.brianstacks.project1.JSONParser;
import com.brianstacks.project1.MainActivity;
import com.brianstacks.project1.Places;
import com.brianstacks.project1.PlacesAdapter;
import com.brianstacks.project1.R;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Brian Stacks
* on 10/27/14
* for FullSail.edu.
*/
public class MasterFragment extends ListFragment{
public static final String TAG = "MasterFragment.TAG";
public static final String KEY = "places";
private OnListItemClickListener mListener;
private ArrayList<Places> placeList2;
public static MasterFragment newInstance(ArrayList<Places> placeList) {
MasterFragment masterFragment = new MasterFragment();
Bundle args = new Bundle();
args.putSerializable("places", placeList);
masterFragment.setArguments(args);
return masterFragment;
}
public interface OnListItemClickListener{
public void displayText(String myText);
}
#Override
public void onAttach(Activity activity){
super.onAttach(activity);
if (activity instanceof OnListItemClickListener){
mListener = (OnListItemClickListener) activity;
}else {
throw new IllegalArgumentException("Containing Activity must implement the OnListItemClicked");
}
}
#Override
public void onActivityCreated(Bundle _savedInstanceState) {
super.onActivityCreated(_savedInstanceState);
if (_savedInstanceState == null){
Bundle args = getArguments();
String myStrings=args.getString("places");
Log.v("Places",myStrings);
/*String[] presidents = getResources().getStringArray(R.array.presidents);
//ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, presidents);
//PlacesAdapter adapter2 = new PlacesAdapter(this.getActivity(),R.layout.item_place,placeList);
//setListAdapter(adapter2);
}
#Override
public void onListItemClick(ListView _l, View _v, int _position, long _id) {
String president = (String)_l.getItemAtPosition(_position);
mListener.displayText(president);
*/
}
}
}
HTTPManager.java
package com.brianstacks.project1;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by Brian Stacks
* on 10/20/14
* for FullSail.edu.
*/
public class HttpManager {
public static String getData(String uri){
BufferedReader reader = null;
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while ((line = reader.readLine()) != null){
sb.append(line).append("");
}
return sb.toString();
}catch (Exception e){
e.printStackTrace();
return null;
}finally {
if (reader!=null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
JSONParser.java
package com.brianstacks.project1;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Brian Stacks
* on 10/20/14
* for FullSail.edu.
*/
public class JSONParser {
public static ArrayList<Places> parseFeed(String content) {
JSONObject myObj;
try {
myObj = new JSONObject(content);
JSONArray result = myObj.getJSONArray("results");
ArrayList<Places> placeList = new ArrayList<>();
for (int i = 0; i < result.length(); i++) {
JSONObject obj = result.getJSONObject(i);
Places place = new Places();
place.setName(obj.getString("name"));
place.setFormatted_address(obj.getString("formatted_address"));
place.setTypes(obj.getString("types"));
//place.setPhotos(obj.getString("photos"));
placeList.add(place);
}
return placeList;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
}
Places.java
import java.io.Serializable;
/**
* Created by Brian Stacks
* on 10/22/14
* for FullSail.edu.
*/
public class Places implements Serializable {
private String pName;
private String pTypes;
private String pFormatted_address;
public Places(){
pName ="";
pTypes ="";
pFormatted_address = "";
}
public String getName() {
return pName;
}
public void setName(String name) {
pName = name;
}
public String getTypes() {
return pTypes;
}
public void setTypes(String types) {
pTypes= types;
}
public String getFormatted_address() {
return pFormatted_address;
}
public void setFormatted_address(String formatted_address) {
pFormatted_address=formatted_address;
}
}
Any help is much appreciated
ALSO was reading this post but to no avail LINK!
I found my solution to this problem, it was I was trying to cast my Objectin my MasterFragment.java as a String when the code was expecting an ArrayList<Places> changed that bit of code and pow there it was, no error.
Old Code
Bundle args = getArguments();
String myStrings=args.getString("places");
New Code
Bundle args = getArguments();
ArrayList myStrings = args.getParcelableArrayList("places");