Android listview not getting populated with data - java

I am new to Android Studio and have a simple android view i am working on. A button click makes a call to the foursquare API and get backresults for starbucks around my location that I parse and am trying to set to the adapter for the listbox on the same view. If i put a breakpoint in the OnPostExecute() I see the mFoursquare adapter that I set for the listview has two json string results in the mFoursquareAdapter , I even call the
mFoursquareAdapter.notifyDataSetChanged();
in it but the view does not get refreshed with the results. I have posted the code below. Can anyone please point out what I am doing wrong or need to change since I already have the results and need to get this done...Your help and feedback very much appreciated! thanks
public class FoursquareInfoFragment extends android.app.Fragment {
private ArrayAdapter<String> mFoursquareAdapter;
public FoursquareInfoFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Dummy data for the ListView. Here's the sample weekly forecast
String[] data = {
"Sample Foursquare Data",
};
List<String> foursquareList = new ArrayList<String>(Arrays.asList(data));
mFoursquareAdapter = new ArrayAdapter<String>(
getActivity(), // the current context ie the activity
R.layout.fragment_my, // the name of the layout Id
R.id.textViewFoursquare, // the Id of the TextView to populate
foursquareList);
View rootView = inflater.inflate(R.layout.fragment_my, container, false);
//View resultsView = inflater.inflate(R.layout.results, container, false);
View resultsView = inflater.inflate(R.layout.fragment_my, container, false);
ListView listView = (ListView) resultsView.findViewById(R.id.listview_FoursquareInfo);
listView.setAdapter(mFoursquareAdapter);
Button btnGetFoursquareData = (Button) rootView.findViewById(R.id.btnFoursquare);
btnGetFoursquareData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FetchFoursquareDataTask fetch = new FetchFoursquareDataTask();
fetch.execute("Starbucks");
}
});
return rootView;
}
public class FetchFoursquareDataTask extends AsyncTask<String, Void, String[]> {
private final String LOG_TAG = FetchFoursquareDataTask.class.getSimpleName();
#Override
protected void onPostExecute(String[] result) {
if (result != null) {
mFoursquareAdapter.clear();
for (String ItemStr : result) {
mFoursquareAdapter.add(ItemStr);
}
mFoursquareAdapter.notifyDataSetChanged();
}
}
#Override
protected String[] doInBackground(String... params) {
// If there's no venue category, theres nothing to look up. Verify the size of the params.
if (params.length == 0) {
return null;
}
// 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 foursquareJsonStr = null;
try {
// Build Foursquare URI with Parameters
final String FOURSQUARE_BASE_URL =
"https://api.foursquare.com/v2/venues/search";
final String client_id = "client_id";
final String client_secret = "client_secret";
final String v = "20130815";
final String near = "Dunwoody, Ga";
final String query = "Starbucks";
final String limit = "2";
Uri builtUri = Uri.parse(FOURSQUARE_BASE_URL).buildUpon()
.appendQueryParameter("client_id", client_id)
.appendQueryParameter("client_secret", client_secret)
.appendQueryParameter("v", v)
.appendQueryParameter("near", near)
.appendQueryParameter("query", query)
.appendQueryParameter("limit", limit)
.build();
URL url = new URL(builtUri.toString());
// Create the request to Foursquare, and open the connection
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.
foursquareJsonStr = null;
return null;
}
foursquareJsonStr = buffer.toString();
Log.v(LOG_TAG, "Foursquare JSON String: " + foursquareJsonStr);
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
// If the code didn't successfully get the fpursquare 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("PlaceholderFragment", "Error closing stream", e);
}
}
}
String[] list = new String[]{"", ""};
try {
JSONObject foursquareJson = new JSONObject(foursquareJsonStr);
JSONObject responseObject = (JSONObject) foursquareJson.get("response");
JSONArray foursquareArray = responseObject.getJSONArray("venues");
list = new String[foursquareArray.length()];
for (int i = 0; i < foursquareArray.length(); i++) {
list[i] = foursquareArray.get(i).toString();
}
return list;
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
} finally {
Log.e(LOG_TAG, "ba");
return list;
}
}
}
}

This
mFoursquareAdapter.add(ItemStr);
Should be
foursquareList.add(ItemStr)
And you'll need to declare foursquareList properly (as a field).
You should also declare your Adapter as a field variable as well, just in case you need to reference it later

Related

why ListView does not filled while I am using AsyncTask?

I am writing an app that uses Google book search API , what the app suppose to do is to display a list of books based on a search query that i provide within the app's code as a String, i use an AsyncTask inner class to handle the background work (making HTTP request , JSON formatting ...etc), I also have book costume adapter and book class to get the data from , my problem is the app dose not display any book in the list view .
here's my code:
My Activity:
public class MainActivity extends AppCompatActivity {
final static String bookUrl = "https://www.googleapis.com/books/v1/volumes?q=android&maxResults=6";
private BookAdapter bookAdapter;
private ArrayList<Book> books;
private ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.list);
new BookAsynck().execute(bookUrl);
}
private class BookAsynck extends AsyncTask<String, Void, ArrayList<Book>> {
#Override
protected ArrayList<Book> doInBackground(String... strings) {
books = Utils.fetchBookData(bookUrl);
return books;
}
#Override
protected void onPostExecute(ArrayList<Book> books) {
bookAdapter = new BookAdapter(MainActivity.this, books);
list.setAdapter(bookAdapter);
}
}
}
My Util class :
public class Utils {
public static final String LOG_TAG = Utils.class.getSimpleName();
public static ArrayList<Book> fetchBookData(String requestUrl) {
ArrayList<Book> bookList = new ArrayList<>();
URL url = CreateURl(requestUrl);
String json = null;
try {
json = makeHttpRequest(url);
} catch (IOException e) {
Log.e(LOG_TAG, "Error closing input stream", e);
}
bookList = extractBookData(json);
return bookList;
}
public static URL CreateURl(String stringUrl) {
URL url = null;
try {
url = new URL(stringUrl);
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Error with creating URL ", e);
}
return url;
}
//make http request and return a string containing the response
public static String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";
//if the url is null return empty string
if (url == null) {
return jsonResponse;
}
HttpURLConnection urlcon = null;
InputStream inputstream = null;
try {
urlcon = (HttpURLConnection) url.openConnection();
urlcon.setRequestMethod("GET");
urlcon.setReadTimeout(1000 /*milleseconds*/);
urlcon.setConnectTimeout(1500 /*milleseconds*/);
urlcon.connect();
//if the request wass Successul (code 200)
// get the input stream and decode it
if (urlcon.getResponseCode() == 200) {
inputstream = urlcon.getInputStream();
jsonResponse = readFromStream(inputstream);
} else {
Log.e(LOG_TAG, "Error response code " + urlcon.getResponseCode());
}
} catch (IOException e) {
Log.e(LOG_TAG, "Problem retrieving the book JSON results", e);
} finally {
if (urlcon != null) {
urlcon.disconnect();
}
if (inputstream != null) {
inputstream.close();
}
}
return jsonResponse;
}
//decode the inputstream into string that conatin the Jsresponse from the Server
private static String readFromStream(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null) {
output.append(line);
line = reader.readLine();
}
}
return output.toString();
}
public static ArrayList<Book> extractBookData(String json) {
ArrayList<Book> booklist = new ArrayList<>();
if (TextUtils.isEmpty(json)) {
return null;
}
try {
JSONObject base = new JSONObject(json);
JSONArray itemsArray = base.optJSONArray("items");
for (int i = 0; i < itemsArray.length(); i++) {
JSONObject first = itemsArray.getJSONObject(i);
JSONObject volume = new JSONObject("volumeInfo");
String title = volume.getString("title");
JSONArray authorsArray = volume.getJSONArray("authors");
String author = authorsArray.getString(0);
Book b = new Book(title, author);
booklist.add(b);
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Problem parsing the book JSON results", e);
}
return booklist;
}
}
My Book Adapter:
public class BookAdapter extends ArrayAdapter<Book> {
public BookAdapter(Context c, ArrayList<Book> book) {
super(c, 0, book);
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View list = convertView;
if (list == null) {
list = LayoutInflater.from(getContext()).inflate(R.layout.item, parent, false);
}
Book b = getItem(position);
TextView titleTextView = (TextView) list.findViewById(R.id.title);
titleTextView.setText(b.getName());
TextView author = (TextView) list.findViewById(R.id.author);
author.setText(b.getAuthor());
return list;
}
}
It looks like you missed calling your asynctask inside activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.list);
new BookAsynck().execute(bookUrl);
}
Welcome to stackoverflow !!
Beginning at Android 9, requests without encryption will not work, that means HttpsURLConnection will work but HttpURLConnection will not.
Then the URL you try to connect must have a https:// access or you should include this in your manifest
android:usesCleartextTraffic="true"
Change the below line from onCreate()
ListView list = (ListView) findViewById(R.id.list);
to
list = (ListView) findViewById(R.id.list);

Array of images loops itself in each item in my array list of object

Please help me out
I am fetching image from a JSON API to my android app for each item in my arraylist. The images are fetching correctly, but instead of setting only the image that is meant for each list item, it is looping and interchanging all the images in all the list on one item and all the list items respectively, thereby making the image in each list item to be changing to different images in seconds.
See the JSON file
{ "data":[
{
"sno":1,
"id":"3",
"title":"This Is Great Again",
"desc":"The details of how a UUID is generated are determined by the device manufacturer and are specific to the device's platform or model.The details of...",
"free":"Yes",
"image":"http:\/\/app-web.moneyacademy.ng\/uploads\/145277f3d0499ee8e0dafbac384ca9b4.jpg",
"date_added":"2017-10-12 10:26PM",
"no_comment":3,
"comments":[ ]
},
{
"sno":2,
"id":"6",
"title":"Money Makes The World Go Round",
"desc":"On this realm, nothing works without money. You need to get some of it or else you'll be grounded.",
"free":"Yes",
"image":"http:\/\/app-web.moneyacademy.ng\/uploads\/546a4c29a94f3d70ae9a075ce8afcc6b.jpg",
"date_added":"2018-02-18 10:06AM",
"no_comment":0,
"comments":[ ]
},
{
"sno":3,
"id":"7",
"title":"No One Is Destined To Be Poor",
"desc":"You will not be poor.",
"free":"Yes",
"image":"http:\/\/app-web.moneyacademy.ng\/uploads\/8f19b9cebd1ca4dec74fafcfe23ae0f0.jpg",
"date_added":"2018-02-18 01:03PM",
"no_comment":0,
"comments":[ ]
},
{
"sno":4,
"id":"8",
"title":"What Is Your Money?",
"desc":"Understand the true definition of your money.",
"free":"Yes",
"image":"http:\/\/app-web.moneyacademy.ng\/uploads\/49b35ffb5cabcb7e01dab2d452ec6025.jpg",
"date_added":"2018-02-18 01:30PM",
"no_comment":0,
"comments":[ ]
},
Here is my code for fetching each item and the image
private static ArrayList<nauget> extractFeatureFromJson(String freeNaugetJson) {
// If the JSON string is empty or null, then return early.
if (TextUtils.isEmpty(freeNaugetJson)) {
return null;
}
ArrayList<nauget> naugets = new ArrayList<nauget>();
try {
JSONObject baseJsonResponse = new JSONObject(freeNaugetJson);
JSONArray dataArray = baseJsonResponse.getJSONArray("data");
// If there are results in the data array
for (int i = 0; i < dataArray.length(); i++){
String title = dataArray.getJSONObject(i).getString("title");
String body = dataArray.getJSONObject(i).getString("desc");
String totalComments = dataArray.getJSONObject(i).getString("no_comment");
String image = dataArray.getJSONObject(i).getString("image");
int id = dataArray.getJSONObject(i).getInt("id");
ArrayList<Comment> comments = new ArrayList<Comment>();
//fetch each comment detail
if (Integer.parseInt(totalComments) > 0) {
JSONArray commentArray = dataArray.getJSONObject(i).getJSONArray("comments");
for (int j = 0; j < commentArray.length(); j++) {
String userName = commentArray.getJSONObject(j).getString("userName");
String comment_image = commentArray.getJSONObject(j).getString("userPhoto");
String comment = commentArray.getJSONObject(j).getString("comment");
String date = commentArray.getJSONObject(j).getString("date_commented");
comments.add(new Comment(userName, comment_image, comment, date));
}
}
// Create a new nauget object
naugets.add(new nauget(title, body, image, totalComments, comments, id));
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Problem parsing the nauget JSON results", e);
}
return naugets;
}
Here is my custom adapter code where am setting the image and its text data for each list item.
public class NaugetAddapter extends ArrayAdapter<nauget> {
ArrayList<nauget> naugets;
private nauget currentNauget;
private ImageView naugetImage;
private TextView naugetTitle;
private TextView naugetBody;
private TextView commentCount;
public NaugetAddapter(#NonNull Context context, ArrayList<nauget> naugets) {
super(context, 0, naugets);
}
#NonNull
#Override
public View getView(final int position, #Nullable View convertView, #NonNull ViewGroup parent) {
//check if the convert view is null and inflate the view
if (convertView == null){
convertView = LayoutInflater.from(getContext()).inflate(R.layout.free_nauget_item, parent, false);
}
currentNauget = (nauget) getItem(position);
//find the nauget title textView and set the text
naugetTitle = (TextView) convertView.findViewById(R.id.nauget_title);
naugetTitle.setText(currentNauget.getNauget_title());
//find the nauget body textView and set the text
naugetBody = (TextView) convertView.findViewById(R.id.nauget_body);
naugetBody.setText(currentNauget.getNauget_body());
//set the nauget total comment count
commentCount = (TextView) convertView.findViewById(R.id.comment_count);
commentCount.setText(currentNauget.getNaugetTotalComments());
//set the comment text
TextView commentText = (TextView) convertView.findViewById(R.id.comment_text);
commentText.setText(currentNauget.getNaugetCommentText());
//set the nauget image
naugetImage = (ImageView) convertView.findViewById(R.id.nauget_image);
new DownloadImageTask().execute(currentNauget.getImageUrl());
//set the share icon
ImageView shareIcon = (ImageView) convertView.findViewById(R.id.share_icon);
shareIcon.setImageResource(currentNauget.getNaugetShareIcon());
//set share functionality on the share icon
shareIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "My App");
shareIntent.putExtra(Intent.EXTRA_TEXT,
naugetTitle.getText()
+ "\n" + naugetBody.getText()
+ "\n" + naugetImage.getDrawable());
startActivity(getContext(), Intent.createChooser(shareIntent, "Share via"), null);
}
});
return convertView;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// mLoadingIndicator.setVisibility(View.VISIBLE);
}
protected Bitmap doInBackground(String... urls) {
Bitmap image = null;
HttpURLConnection urlConnection = null;
try {URL url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
int statusCode = urlConnection.getResponseCode();
if (statusCode != 200) {
return null;
}
InputStream inputStream = urlConnection.getInputStream();
if (inputStream != null) {
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}
} catch (Exception e) {
urlConnection.disconnect();
Log.e("Error", e.getMessage());
e.printStackTrace();
}finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
protected void onPostExecute(Bitmap result) {
// mLoadingIndicator.setVisibility(View.INVISIBLE);
naugetImage.setImageBitmap(result);
}
}
#NonNull
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
ArrayList<nauget> filteredResults = new ArrayList<>();
FilterResults results = new FilterResults();
results.values = filteredResults;
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
}
};
}
void setFilter(ArrayList<nauget> listItem){
naugets = new ArrayList();
naugets.addAll(listItem);
notifyDataSetChanged();
}
}
This should solve the issue! you are trying everything fine but you have the comment ArrayList inside of a loop getting instantiated each time newly just put it before the outer loop as I did here and the error should go! TRY IT
try {
JSONObject baseJsonResponse = new JSONObject(freeNaugetJson);
JSONArray dataArray = baseJsonResponse.getJSONArray("data");
//put it here so you won't get a new array for each comment in the loop
**ArrayList<Comment> comments = new ArrayList<Comment>();**
// If there are results in the data array
for (int i = 0; i < dataArray.length(); i++){
String title = dataArray.getJSONObject(i).getString("title");
String body = dataArray.getJSONObject(i).getString("desc");
String totalComments = dataArray.getJSONObject(i).getString("no_comment");
String image = dataArray.getJSONObject(i).getString("image");
int id = dataArray.getJSONObject(i).getInt("id");
//here after every comment check its making a new comment ArrayList for each comment and filling it out so this can be the cause of the bug! bcz its in the loop
// ArrayList<Comment> comments = new ArrayList<Comment>();
//fetch each comment detail
if (Integer.parseInt(totalComments) > 0) {
JSONArray commentArray = dataArray.getJSONObject(i).getJSONArray("comments");
for (int j = 0; j < commentArray.length(); j++) {
String userName = commentArray.getJSONObject(j).getString("userName");
String comment_image = commentArray.getJSONObject(j).getString("userPhoto");
String comment = commentArray.getJSONObject(j).getString("comment");
String date = commentArray.getJSONObject(j).getString("date_commented");
comments.add(new Comment(userName, comment_image, comment, date));
}
}
// Create a new nauget object
naugets.add(new nauget(title, body, image, totalComments, comments, id));
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Problem parsing the nauget JSON results", e);
}
return naugets;

AsyncTask not create GridView using BaseAdpter

Im new to android development have very basic knowledge of this whatever i have achieved till now is achieved using this website or youtube videos i'm stuck in AsyncTask (Earlier i was using .get() on Create View and it was working fine but UI Was blocked until task is finished. To Avoid UI Blocking i was advice to remove .get() function from OnCreateView() function now after removing this im not being able to get any data from AsyncTask). I did that but now i'm not being able to create view i did lots of research but unable to get this strength
Here is my Codes Please Help how to create view from this
OnCreateView() :-
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View GView = inflater.inflate(R.layout.fragment_dashboard, container, false);
progressBarHolder = (FrameLayout) GView.findViewById(R.id.progressBarHolder);
GridView gridView = (GridView) GView.findViewById(R.id.gridView);
//Toast.makeText(getActivity(),Json_String,Toast.LENGTH_LONG).show();
String finalResult = null;
try{
finalResult = String.valueOf(new JSONTask().execute("https://www.example.in/android_api/dashboard_data",JsonData()));
Toast.makeText(getActivity(),Json_String,Toast.LENGTH_LONG).show();
JSONObject parentObject = null;
parentObject = new JSONObject(finalResult);
if(((String) parentObject.names().get(0)).matches("error")){
JSONObject jObj = parentObject.getJSONObject("error");
errorThrow(jObj.getString("Description"));
} else if(((String) parentObject.names().get(0)).matches("success")){
JSONObject jObj = parentObject.getJSONObject("success");
JSONArray arrajson = jObj.getJSONArray("data");
String arrayCount = Integer.toString(arrajson.length());
String[] type = new String[arrajson.length()];
Integer[] count = new Integer[arrajson.length()];
for (int i=0; i<arrajson.length();i++){
JSONObject jsonObject = arrajson.getJSONObject(i);
type[i] = jsonObject.getString("type");
count[i] = jsonObject.getInt("count");
}
CustomAdpter customAdpter = new CustomAdpter(DashboardFragment.this,type,count);
gridView.setAdapter(customAdpter);
return GView;
}
} catch (JSONException e) {
e.printStackTrace();
}
return GView;
}
Base Adapter Code :-
class CustomAdpter extends BaseAdapter {
String[] type;
Integer[] count;
public CustomAdpter(DashboardFragment dashboardFragment, String[] type, Integer[] count){
this.count = count;
this.type = type;
}
#Override
public int getCount() {
return type.length;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = getLayoutInflater().inflate(R.layout.grid_single_itme,null);
TextView textView = (TextView) view.findViewById(R.id.TextView1);
TextView textView1 = (TextView) view.findViewById(R.id.textView2);
textView.setText(String.valueOf(count[i]));
textView1.setText(type[i]);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(),"Booking Item Clicked",Toast.LENGTH_LONG).show();
}
});
return view;
}
}
AsyncTask Code :-
public class JSONTask extends AsyncTask<String,String,String> {
private ProgressDialog mProgressDialog;
int progress;
public JSONTask(){
mProgressDialog = new ProgressDialog(getContext());
mProgressDialog.setMax(100);
mProgressDialog.setProgress(0);
}
#Override
protected void onPreExecute(){
mProgressDialog = ProgressDialog.show(getContext(),"Loading","Loading Data...",true,false);
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
final String finalJson = params[1];
String json = finalJson;
try{
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(5000);
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
connection.setRequestProperty("A-APK-API", "******");
connection.setRequestProperty("Authorization", "Basic **:**");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.connect();
OutputStream stream = connection.getOutputStream();
OutputStreamWriter streams = new OutputStreamWriter(stream, "UTF-8");
stream.write(json.getBytes("UTF-8"));
stream.close();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
StringBuffer buffer = new StringBuffer();
String line = "";
while((line = reader.readLine()) != null){
buffer.append(line);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(connection != null){
connection.disconnect();
}
try {
if(reader != null) {
reader.close();
}
} catch (IOException e){
e.printStackTrace();
}
}
return null;
}
protected void onPostExecute(String result){
super.onPostExecute(result);
Json_String = result;
Toast.makeText(getContext(),result,Toast.LENGTH_LONG).show();
mProgressDialog.dismiss();
}
}
Please help me here
You cannot get a result from asynctask when you dont use .get().
So change that statement. Start only the asynctask.
Then put all the code after that line in onPostExecute() of the AsyncTask.
Thats all.
you should change way you are creating the Adapter and attaching
you should do this
1.At first get the data in List,ArrayList etc. via AsyncTask, doInBackGround method
then on the onPostExecute method retrieve the data and create Adapter and attach it to your View
While you are getting data you can show some ProgressDialog.
If your AsyncTask is in other separate class then use interface to get the data from your AsyncTask class
look at this https://stackoverflow.com/a/47373959/8197737

NullPointerException come out into onPostExecute Method [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
public class MainFragment extends Fragment {
//private poster_adapter movieInfos;
private ArrayAdapter<MovieInfo> movieInfos;
private String LOG_TAG = MainFragment.class.getSimpleName();
public MainFragment() {
}
#Override
public void onStart() {
super.onStart();
FetchMovieInfo update = new FetchMovieInfo();
update.execute();
Log.d(LOG_TAG, Thread.currentThread().getStackTrace()[2].getMethodName());
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Log.d(LOG_TAG, Thread.currentThread().getStackTrace()[2].getMethodName());
/*movieInfos = new ArrayAdapter<String>(
getActivity(),
R.layout.poster_item_layout,
R.id.poster_item,
new ArrayList<String>()
);*/
View rootView = inflater.inflate(R.layout.activity_main_fragment, container, false);
// Log.d(LOG_TAG,movieInfos[]);
//infoAdapter = new poster_adapter(getActivity(), Arrays.asList(movieInfos));
GridView gridView = (GridView) rootView.findViewById(R.id.gridview);
gridView.setAdapter(movieInfos);
return rootView;
}
public class FetchMovieInfo extends AsyncTask<Void, Void, String[]> {
String LOG_TAG = MainActivity.class.getSimpleName();
private String[] getMovieInfoFromJSON(String moviesInfoJSONStr) throws JSONException {
Log.d(LOG_TAG, Thread.currentThread().getStackTrace()[2].getMethodName().toString());
JSONObject moviesInfoJSON = new JSONObject(moviesInfoJSONStr);
JSONArray movieInfoJSON = moviesInfoJSON.getJSONArray("results");
String[] poster_urls = new String[movieInfoJSON.length()];
for (int i = 0; i < movieInfoJSON.length(); i++) {
JSONObject movieInfo = movieInfoJSON.getJSONObject(i);
poster_urls[i] = movieInfo.getString("poster_path");
}
return poster_urls;
}
#Override
protected String[] doInBackground(Void... params) {
Log.d(LOG_TAG, Thread.currentThread().getStackTrace()[2].getMethodName().toString());
HttpURLConnection httpURLConnection = null;
BufferedReader reader = null;
String movieInfoStr = null;
try {
final String BASE_URL = "http://api.themoviedb.org/3/movie/popular?";
final String API_KEY_PARAM = "api_key";
Uri builtUri = Uri.parse(BASE_URL).buildUpon()
.appendQueryParameter(API_KEY_PARAM, BuildConfig.OPEN_MOVIE_INFO_API_KEY)
.build();
URL url = new URL(builtUri.toString());
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.connect();
InputStream inputStream = httpURLConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
return null;
}
movieInfoStr = buffer.toString();
} catch (IOException e) {
Log.e(LOG_TAG, "Error" + e);
return null;
} finally {
if (httpURLConnection != null)
httpURLConnection.disconnect();
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error" + e);
}
}
}
try {
return getMovieInfoFromJSON(movieInfoStr);
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String[] results) {
Log.d(LOG_TAG, Thread.currentThread().getStackTrace()[2].getMethodName().toString());
if (results != null) {
movieInfos.clear();
for (String movieInfo : results) {
movieInfos.add(new MovieInfo(movieInfo));
}
}
}
}
}
Here is code.
When i was debugging,NullPointerException will come out as soon as i step into onPostExecute method.
I want to put some path string into my movie info adapter.
And when i was debugging,it will stop at some other libraries instead of code i wrote.
Your ArrayAdapter movieInfos was not instantiated. So when it ran to the line
movieInfos.clear();
NullPointerException wolud come out.
In your method onCreateView,you comment these code out:
/*movieInfos = new ArrayAdapter<String>(
getActivity(),
R.layout.poster_item_layout,
R.id.poster_item,
new ArrayList<String>()
);*/
So the movieInfos is a null object,never instantiated.Please cancel commenting these code out,you should instance movieInfos before your use it.

Results not showing in the ListView Android

I've been working on an android app ... I am stuck at a point ... after getting the JSON data from the internet I am having trouble to show it in the ListView ... Below is my code ...
public class MainListActivityFragment extends Fragment {
protected String[] mBlogPostTitles;
protected JSONObject mBlogData;
public static final String LOG_TAG = MainListActivityFragment.class.getSimpleName();
public static ArrayAdapter<String> titleAdapter;
public MainListActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_list, container, false);
if(isNetworkAvailable()) {
GetBlogPost getBlogPost = new GetBlogPost();
getBlogPost.execute();
} else {
Toast.makeText(getContext(),"No Network Available", Toast.LENGTH_LONG).show();
}
List<String> blogTitles = new ArrayList<>(Arrays.asList(mBlogPostTitles));
titleAdapter = new ArrayAdapter<>(
getActivity(),
R.layout.name_lst_view,
R.id.name_list_view_textview,
blogTitles
);
ListView listView = (ListView) rootView.findViewById(R.id.listview_name);
listView.setAdapter(titleAdapter);
return rootView;
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()){
isAvailable = true;
}
return isAvailable;
}
private void updateList() {
if(mBlogData == null){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Oopps");
builder.setMessage("There was an error accessing the blog ...");
builder.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}else {
try {
JSONArray jsonPosts = mBlogData.getJSONArray("posts");
mBlogPostTitles = new String[jsonPosts.length()];
for (int i = 0; i < jsonPosts.length(); i++){
JSONObject post = jsonPosts.getJSONObject(i);
String title = post.getString("title");
title = Html.fromHtml(title).toString();
mBlogPostTitles[i] = title;
}
} catch (JSONException e) {
Log.e(LOG_TAG,"Exception Caught: ",e);
}
}
}
public class GetBlogPost extends AsyncTask<Object, Void, JSONObject> {
public final int NUMBER_OF_POSTS = 5;
int responseCode = -1;
JSONObject jsonResponse = null;
#Override
protected JSONObject doInBackground(Object... params) {
try {
URL blogFeedUrl = new URL("http://www.example.com/api/get_category_posts/?slug=americancuisines&count="+NUMBER_OF_POSTS);
HttpURLConnection connection = (HttpURLConnection) blogFeedUrl.openConnection();
connection.setRequestMethod("GET");
connection.connect();
responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK){
InputStream inputStream = connection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
BufferedReader 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;
}
String blogDataJsonStr = buffer.toString();
jsonResponse = new JSONObject(blogDataJsonStr);
}else {
Log.i(LOG_TAG, "Unsuccessful HTTP Response Code: " + responseCode);
}
}
catch (MalformedURLException e){
Log.e(LOG_TAG,"Exception Caught: ",e);
}
catch (IOException e) {
Log.e(LOG_TAG, "IO Exception Caught: ",e);
}
catch (Exception e) {
Log.e(LOG_TAG,"Exception Caught: ",e);
}
return jsonResponse;
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
mBlogData = result;
updateList();
}
}
}
From the above code you can see that i am getting that data through doInBackground method of AsyncTask ... Data is coming through perfectly as I can see through the logcat ... The issue is somewhere in this method which I can't seem to figure out ..
private void updateList() {
if(mBlogData == null){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Oopps");
builder.setMessage("There was an error accessing the blog ...");
builder.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}else {
try {
JSONArray jsonPosts = mBlogData.getJSONArray("posts");
mBlogPostTitles = new String[jsonPosts.length()];
for (int i = 0; i < jsonPosts.length(); i++){
JSONObject post = jsonPosts.getJSONObject(i);
String title = post.getString("title");
title = Html.fromHtml(title).toString();
mBlogPostTitles[i] = title;
}
} catch (JSONException e) {
Log.e(LOG_TAG,"Exception Caught: ",e);
}
}
}
The above method is called in onPostExecute I mean if i print to logcat within this method I can see the results being printed but when I try to show those results in the onCreateView method results don't show up not even in the logcat ... Any help will be appreciated ... Thanks
Change your code as following:
public class MainListActivityFragment extends Fragment {
protected String[] mBlogPostTitles;
protected JSONObject mBlogData;
public static final String LOG_TAG = MainListActivityFragment.class.getSimpleName();
public static ArrayAdapter<String> titleAdapter;
ListView listView;
public MainListActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_list, container, false);
listView = (ListView) rootView.findViewById(R.id.listview_name);
if(isNetworkAvailable()) {
GetBlogPost getBlogPost = new GetBlogPost();
getBlogPost.execute();
} else {
Toast.makeText(getContext(),"No Network Available", Toast.LENGTH_LONG).show();
}
return rootView;
}
private void updateList() {
if(mBlogData == null){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Oopps");
builder.setMessage("There was an error accessing the blog ...");
builder.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}else {
try {
JSONArray jsonPosts = mBlogData.getJSONArray("posts");
mBlogPostTitles = new String[jsonPosts.length()];
for (int i = 0; i < jsonPosts.length(); i++){
JSONObject post = jsonPosts.getJSONObject(i);
String title = post.getString("title");
title = Html.fromHtml(title).toString();
mBlogPostTitles[i] = title;
}
} catch (JSONException e) {
Log.e(LOG_TAG,"Exception Caught: ",e);
}
}
}
public class GetBlogPost extends AsyncTask<Object, Void, JSONObject> {
public final int NUMBER_OF_POSTS = 5;
int responseCode = -1;
JSONObject jsonResponse = null;
#Override
protected JSONObject doInBackground(Object... params) {
try {
URL blogFeedUrl = new URL("http://www.example.com/api/get_category_posts/?slug=americancuisines&count="+NUMBER_OF_POSTS);
HttpURLConnection connection = (HttpURLConnection) blogFeedUrl.openConnection();
connection.setRequestMethod("GET");
connection.connect();
responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK){
InputStream inputStream = connection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
BufferedReader 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;
}
String blogDataJsonStr = buffer.toString();
jsonResponse = new JSONObject(blogDataJsonStr);
}else {
Log.i(LOG_TAG, "Unsuccessful HTTP Response Code: " + responseCode);
}
}
catch (MalformedURLException e){
Log.e(LOG_TAG,"Exception Caught: ",e);
}
catch (IOException e) {
Log.e(LOG_TAG, "IO Exception Caught: ",e);
}
catch (Exception e) {
Log.e(LOG_TAG,"Exception Caught: ",e);
}
return jsonResponse;
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
mBlogData = result;
updateList();
List<String> blogTitles = new ArrayList<>(Arrays.asList(mBlogPostTitles));
titleAdapter = new ArrayAdapter<String>(
getActivity(),
R.layout.name_list_view,
R.id.name_list_view_textview,
blogTitles
);
listView.setAdapter(titleAdapter);
}
}
}
Use same array list in both update and initialize so globally declare a single array list and update it in updateList() method,
Try like this,
try {
JSONArray jsonPosts = mBlogData.getJSONArray("posts");
mBlogPostTitles = new String[jsonPosts.length()];//remove this and use the
//same as you are using in adapter
for (int i = 0; i < jsonPosts.length(); i++){
JSONObject post = jsonPosts.getJSONObject(i);
String title = post.getString("title");
title = Html.fromHtml(title).toString();
mBlogPostTitles[i] = title;
}
titleAdapter.notifyDataSetChanged();//here
} catch (JSONException e) {
Log.e(LOG_TAG,"Exception Caught: ",e);
}
OR even you can use in onPostExecute
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
mBlogData = result;
updateList();
titleAdapter.notifyDataSetChanged();//here
}
find the listview : ListView listView = (ListView) rootView.findViewById(R.id.listview_name); before calling
GetBlogPost getBlogPost = new GetBlogPost();
getBlogPost.execute();
and put this line listView.setAdapter(titleAdapter); in your onPostExecute method.

Categories

Resources