Empty string when reading data sent from server - java

I'm having trouble with this code. The variable result should be filled from the response of the server, but for any reason, it keeps returning an empty string.
This is the entire code:
public class FragmentRally extends Fragment {
public FragmentRally() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_fragment_rally, container, false);
new AsyncFetch().execute();
return rootView;
}
// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private RecyclerView vistaRallye;
private AdapterRallye adaptadorRallye;
private class AsyncFetch extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(getActivity());
HttpURLConnection conn;
URL url = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tCarregant...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(String... params) {
try {
// Enter URL address where your json file resides
// Even you can make call to php file which returns json data
url = new URL("http://www.rallyecat.esy.es/Obtenir_events.php");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("GET");
// setDoOutput to true as we recieve data from json file
conn.setDoOutput(true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("No hi ha connexió a internet.");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
//this method will be running on UI thread
pdLoading.dismiss();
List<DataRallye> data = new ArrayList<>();
pdLoading.dismiss();
try {
JSONArray jArray = new JSONArray(result);
// Extract data from json and store into ArrayList as class objects
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
DataRallye dadesrallye = new DataRallye();
dadesrallye.RallyeNom = json_data.getString("nom");
dadesrallye.RallyeTipus = json_data.getString("tipus");
dadesrallye.RallyeDataI = json_data.getString("datai");
dadesrallye.RallyeDataF = json_data.getString("dataf");
dadesrallye.RallyeCiutat = json_data.getString("ciutat");
dadesrallye.RallyeOrganitzacio = json_data.getString("organitzacio");
dadesrallye.RallyeFoto = json_data.getString("foto");
data.add(dadesrallye);
}
// Setup and Handover data to recyclerview
vistaRallye = (RecyclerView) getView().findViewById(R.id.llistarallyes);
adaptadorRallye = new AdapterRallye(getActivity(), data);
vistaRallye.setAdapter(adaptadorRallye);
vistaRallye.setLayoutManager(new LinearLayoutManager(getActivity()));
} catch (JSONException e) {
Toast.makeText(getActivity(), e.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
The problem appears here:
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
This variable, RESULT is passed here, where I do the JSON Parse. But as it is empty, it goes directly to the catch exception:
#Override
protected void onPostExecute(String result) {
//this method will be running on UI thread
pdLoading.dismiss();
List<DataRallye> data = new ArrayList<>();
pdLoading.dismiss();
try {
JSONArray jArray = new JSONArray(result);
// Extract data from json and store into ArrayList as class objects
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
DataRallye dadesrallye = new DataRallye();
dadesrallye.RallyeNom = json_data.getString("nom");
dadesrallye.RallyeTipus = json_data.getString("tipus");
dadesrallye.RallyeDataI = json_data.getString("datai");
dadesrallye.RallyeDataF = json_data.getString("dataf");
dadesrallye.RallyeCiutat = json_data.getString("ciutat");
dadesrallye.RallyeOrganitzacio = json_data.getString("organitzacio");
dadesrallye.RallyeFoto = json_data.getString("foto");
data.add(dadesrallye);
}
// Setup and Handover data to recyclerview
vistaRallye = (RecyclerView) getView().findViewById(R.id.llistarallyes);
adaptadorRallye = new AdapterRallye(getActivity(), data);
vistaRallye.setAdapter(adaptadorRallye);
vistaRallye.setLayoutManager(new LinearLayoutManager(getActivity()));
} catch (JSONException e) {
Toast.makeText(getActivity(), e.toString(), Toast.LENGTH_LONG).show();
}
Here is the JSON generated from a PHP file on our website:
[{"id_rally":"1","nom":"45e rallye costa brava","tipus":"velocitat i regularitat","datai":"2017-06-20","dataf":"2017-06-22","ciutat":"Girona","organitzacio":"rallyclassics ","foto":"brava.png"},{"id_rally":"2","nom":"26e rallye igualada","tipus":"velocitat","datai":"2017-08-13","dataf":"2017-08-16","ciutat":"Igualada","organitzacio":"ecb org","foto":"igualada.png"}]

conn.setDoOutput(true);.
Remove that line. As you will not write data to the outputstream.
result.append(line);
That should be
result.append(line) + "\n";

For 'GET' connections set
conn.setDoOutput(false);
setDoOutput(true) is used for POST and PUT requests.

Related

Hello i am trying to display json data from url into listview. Nothing is displayed though

Url
private static String JSON_URL ="https://run.mocky.io/v3/aff3f637-d04f-45c0-b002-09be1a143784";
ArrayList<HashMap<String,String>> friendsList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
friendsList= new ArrayList<>();
lv = findViewById(R.id.listview);
GetData getData= new GetData();
getData.execute();
}
Getting the data
public class GetData extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... strings) {
String current = "";
try {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(JSON_URL);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(in);
int data = isr.read();
while (data != -1) {
current += (char) data;
data = isr.read();
}
return current;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
} catch (Exception e){
e.printStackTrace();
}
return current;
}
Displaying the data
#Override
protected void onPostExecute(String s) {
try{
JSONObject jsonObject= new JSONObject(s);
JSONArray jsonArray = jsonObject.getJSONArray("Friends"); //name of array
for(int i = 0; i <jsonArray.length();i++)
{
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
namey=jsonObject.getString("name");
age= jsonObject1.getString("age");
//Hashmap
HashMap<String, String> friends = new HashMap<>();
friends.put("name",namey);
friends.put("age", age);
friendsList.add(friends);
}
} catch (JSONException e) {
e.printStackTrace();
}
//Displaying the results
ListAdapter adapter = new SimpleAdapter(
MainActivity.this,
friendsList,
R.layout.row_layout,
new String[]{"name","age"},
new int[]{R.id.textView, R.id.textView2});
lv.setAdapter(adapter);
}
}
}
It doesnt display anything and i believe it has something to do with the url, but i am not quite sure so please help and thank you in advance
Your mocky JSON from https://run.mocky.io/v3/aff3f637-d04f-45c0-b002-09be1a143784 is wrong format, you need to remove the last character

Problem in parsing data from Json Google Places API to recyclerView

I would like to show users a list of bar near by them, without map. I have tried by PlaceLikelihoods, it works fine but I can not put any restriction on the types of place found and it shows a map.
So I searched by URL, but the Try / Catch always leads to the exception, the toast found there shows the good result but the list of recyclerview is not filled.
I found a similar problem that said to move the notifyDataSetChanged(), I have done it.
I find APIs and parsing very complicated to master so it's probably a stupid mistake but it's been 2 weeks and I have not yet succeeded.
Thanks for reading.
public class TestMap extends AppCompatActivity {
// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private LocListAdapter mAdapter;
private EmptyStateRecyclerView mLocRecView;
private ArrayList<LocListUser> data;
private double longitudeUser;
private double latitudeUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loc);
data = new ArrayList<>();
mAdapter = new LocListAdapter(data, TestMap.this);
mLocRecView = findViewById(R.id.locRecView);
mLocRecView.setItemAnimator(new DefaultItemAnimator());
mLocRecView.setLayoutManager(new LinearLayoutManager(TestMap.this));
mLocRecView.setHasFixedSize(true);
//data.clear();
mLocRecView.setAdapter(mAdapter);
mLocRecView.clearStateDisplays();
longitudeUser = getIntent().getDoubleExtra("long", 151.2106085);
latitudeUser = getIntent().getDoubleExtra("lat", -33.8523341);
new AsyncFetch().execute();
}
private class AsyncFetch extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(TestMap.this);
HttpURLConnection conn;
URL url = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(String... params) {
try {
StringBuilder sb;
sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
sb.append("location=").append(latitudeUser).append(",").append(longitudeUser);
sb.append("&radius=5000");
sb.append("&types=" + "bar");
sb.append("&key=API_KEY");
url = new URL(String.valueOf(sb));
} catch (MalformedURLException e) {
e.printStackTrace();
return e.toString();
}
try {
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("GET");
conn.setDoOutput(true);
} catch (IOException e1) {
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
if (response_code == HttpURLConnection.HTTP_OK) {
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
pdLoading.dismiss();
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
LocListUser locList = new LocListUser();
locList.setAddress(json_data.getString("vicinity"));
locList.setId(json_data.getString("reference"));
locList.setName(json_data.getString("place_name"));
locList.setLat(json_data.getJSONObject("geometry").getJSONObject("location").getString("lat"));
locList.setLon(json_data.getJSONObject("geometry").getJSONObject("location").getString("lng"));
locList.setType(json_data.getString("types"));
locList.setLatUser(latitudeUser);
locList.setLonUser(longitudeUser);
data.add(locList);
mAdapter.notifyDataSetChanged();
}
//mAdapter.notifyDataSetChanged();
mLocRecView.invokeState(EmptyStateRecyclerView.STATE_OK);
} catch (JSONException e) { //e.toString()
e.printStackTrace();
}
}
}
}
you are using hardcoded string
JSONArray jArray = new JSONArray("results");
you have to use
JSONArray jArray = new JSONArray(result);

Endless RecyclerView with ProgressBar in Search activity

I am new at android. I have a search activity which searches for a query using async task, i want to implement endless/infinite scrolling when user reaches bottom. I want to add a parameter startrow to async task which will then be passed on to the server telling which row to begin.
// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private RecyclerView mRVFish;
private AdapterFish mAdapter;
private LinearLayoutManager mLayoutManager;
private String searchQuery;
SearchView searchView = null;
private String query;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// adds item to action bar
getMenuInflater().inflate(R.menu.search_main, menu);
// Get Search item from action bar and Get Search service
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchManager searchManager = (SearchManager) MainActivity.this.getSystemService(Context.SEARCH_SERVICE);
if (searchItem != null) {
searchView = (SearchView) searchItem.getActionView();
}
if (searchView != null) {
searchView.setSearchableInfo(searchManager.getSearchableInfo(MainActivity.this.getComponentName()));
searchView.setIconified(false);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
Every time when you press search button on keypad an Activity is recreated which in turn calls this function
#Override
protected void onNewIntent(Intent intent) {
// Get search query and create object of class AsyncFetch
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
query = intent.getStringExtra(SearchManager.QUERY);
if (searchView != null) {
searchView.clearFocus();
}
new AsyncFetch(query).execute();
}
}
class AsyncFetch which will fetch data from the server
private class AsyncFetch extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(MainActivity.this);
HttpURLConnection conn;
URL url = null;
String searchQuery;
public AsyncFetch(String searchQuery){
this.searchQuery=searchQuery;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(String... params) {
try {
// URL address wherephp file resides
url = new URL("http://someurl/json/search.php");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
// setDoInput and setDoOutput to true as we send and recieve data
conn.setDoInput(true);
conn.setDoOutput(true);
// add parameter to our above url
Uri.Builder builder = new Uri.Builder().appendQueryParameter("searchQuery", searchQuery);
String query = builder.build().getEncodedQuery();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return("Connection error");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
//this method will be running on UI thread
pdLoading.dismiss();
List<DataFish> data=new ArrayList<>();
pdLoading.dismiss();
if(result.equals("no rows")) {
Toast.makeText(MainActivity.this, "No Results found for entered query", Toast.LENGTH_LONG).show();
}else{
try {
JSONArray jArray = new JSONArray(result);
// Extract data from json and store into ArrayList as class objects
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
DataFish fishData = new DataFish();
try {
fishData.fileName = URLDecoder.decode(json_data.getString("file"), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
fishData.linkName = json_data.getString("link");
fishData.reg_date = json_data.getString("reg_date");
fishData.fileSize = json_data.getString("filesize");
data.add(fishData);
}
// Setup and Handover data to recyclerview
mRVFish = (RecyclerView) findViewById(R.id.fishPriceList);
mAdapter = new AdapterFish(MainActivity.this, data);
// mRVFish.setLayoutManager(new LinearLayoutManager(MainActivity.this));
mLayoutManager = new LinearLayoutManager(MainActivity.this);
mRVFish.setLayoutManager(mLayoutManager);
mRVFish.setAdapter(mAdapter);
} catch (JSONException e) {
// You to understand what actually error is and handle it appropriately
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
Toast.makeText(MainActivity.this, result.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
Add EndlessScrollListener to recyclerView from link:
https://gist.github.com/zfdang/38ae655a4fc401c99789#file-endlessrecycleronscrolllistener-java
override onLoadMore method and call your AsyncFetch Task.

Android - put data into array in asynctask

I got a question that I don't know how to solve.
I am trying to achieve putting the 'question' and 'answer' into the 2D Array, but it cannot put the data into the 2D array in the asyncTask.
I am expecting I can put the 'question' and 'answer' that get in JSON Object into the 2D array. And then use the array in OnCreate method.
public class MainActivity extends Activity {
String[][] array = new String[10][4];
private TextView tvData;
int qnum = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
String quest;
String ans;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new JSONTask().execute("http://itdmoodle.hung0530.com/ptms/questions_ws.php");
Button btnNext = (Button) findViewById(R.id.btnNext);
tvData = (TextView) findViewById(R.id.textView);
for(int i=0;i<10;i++){
int z = i+1;
array[i][0] = String.valueOf(z);
}
quest = array[0][1];
ans = array[0][2];
tvData.setText(quest);
btnNext.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
}
});
}
public class JSONTask extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... params) {
HttpURLConnection conn = null;
BufferedReader reader = null;
try{
URL url = new URL(params[0]);
conn = (HttpURLConnection) url.openConnection();
conn.connect();
InputStream stream = conn.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line ="";
while((line = reader.readLine()) != null){
buffer.append(line);
}
String Json = buffer.toString();
JSONObject jsonObject = new JSONObject(Json);
JSONArray jsonArray = jsonObject.getJSONArray("Questions");
StringBuffer bufferQues = new StringBuffer();
StringBuffer bufferAns = new StringBuffer();
for(int i=0;i<jsonArray.length();i++) {
JSONObject otherJson = jsonArray.getJSONObject(i);
String question = otherJson.getString("question");
String answer = otherJson.getString("answer");
bufferQues.append(question);
bufferAns.append(answer);
array[i][1] = bufferQues.toString();
array[i][2] = bufferAns.toString();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally{
if(conn != null){
conn.disconnect();
}
try{
if(reader != null){
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
}
}
}
Asynctask executes asynchronously. It allows you to perform long running operations on a background thread(doInBackground is run on a seperate thread than main thread) and use the results to perform operations on main thread(onPostExecute runs on main thread).
What you want is to perform the operation on your 2D array in onPostExecute and not in onCreate.

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