Results not showing in the ListView Android - java

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.

Related

JSON ListView filter not working

So I've got a project to make a simple job board app. I've retrieved my JSON data and have it displaying on my app but I want to be able to use a SearchView filter but I don't know how to access my SimpleAdapter from outside of an inner-class
Here is my code:
public class jobcategories extends Activity{
private TextView jobData;
private ProgressDialog myprocessingdialog;
ArrayAdapter<String> adapter;
ArrayList<HashMap<String, String>> jobList;
private ListView lv;
private SearchView sv;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.jobcategories);
myprocessingdialog = new ProgressDialog(this);
jobList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
sv = (SearchView) findViewById(R.id.search);
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String text) {
return false;
}
#Override
public boolean onQueryTextChange(String text) {
adapter.getFilter().filter(text);
return false;
}
});
new JSONTask().execute("https://apidata.com");
}
public class JSONTask extends AsyncTask<String,String, String>{
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
//Showing Progress dialogue
myprocessingdialog.setTitle("Please Wait..");
myprocessingdialog.setMessage("Loading");
myprocessingdialog.setCancelable(false);
myprocessingdialog.setIndeterminate(false);
myprocessingdialog.show();
}
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try{
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while((line = reader.readLine()) != null){
buffer.append(line);
}
String finalJson = buffer.toString();
JSONArray parentObject = new JSONArray(finalJson);
for (int i=0; i < parentObject.length(); i++) {
JSONObject job = parentObject.getJSONObject(i);
String JobTitle = job.getString("title");
String JobLocation = job.getString("location");
String finalTitle = JobTitle + " in " + JobLocation;
String JobCompany = "advert by "+job.getString("company");
String JobDescription = job.getString("description");
String JobApply = "How to Apply: " + job.getString("apply");
HashMap<String, String> jobs = new HashMap<>();
jobs.put("title", finalTitle);
jobs.put("company", JobCompany);
jobs.put("description", JobDescription);
jobs.put("apply", JobApply);
jobList.add(jobs);
}
}catch (MalformedURLException e){
Toast.makeText(getApplicationContext(), "Error...the job server is down..." + e.toString(), Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "error parsing..." + e.toString(), Toast.LENGTH_LONG).show();
} finally {
if(connection != null) {
connection.disconnect();
}
try {
if(reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String results) {
super.onPostExecute(results);
myprocessingdialog.cancel();
ListAdapter adapter = new SimpleAdapter(
jobcategories.this, jobList,
R.layout.list_item, new String[]{"title", "company", "description", "apply"},
new int[]{R.id.title, R.id.company, R.id.description, R.id.apply});
lv.setAdapter(adapter);
}
}
}
Any help would be appreciated, am pretty new to android so if there is a better way for me to filter the data then I am open to changing the code.
Create an interface called OnJsonResultListener like so:
public interface OnJsonResultListener {
void onResult(String result);
}
Then make your Activity/Fragment implement that interface and do whatever with your simple adapter and the result from there. Then make the AsyncTask take a OnJsonResultListener in the constructor. Then in the onPostExecute method, call listener.onResult(results);
This is a simple way of making a callback.

Empty string when reading data sent from server

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.

Trying to get response from server, but it only displays "Toast Server not responding"

I am trying to get response from server but it only display me toast server not supported.i don't understand what is going on here. i have assigned the api to a static variable that i declare in another class.
Code:
public class SpeakersFrag extends Fragment {
private List<SpeakersBean> dataset;
// private Context context;
private ProgressDialog progressDialog;
SessionContoller sessionContoller;
RecyclerView recyclerView;
public SpeakerAdapter speakerAdapter;
Context context;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View myview=inflater.inflate(R.layout.speakers,null);
this.context=getActivity(); //cmt ctx
this.sessionContoller=new SessionContoller(this.context);
RecyclerView recyclerView = (RecyclerView) myview.findViewById(R.id.Recycler_viewrest);
// List<String> dataSet=new ArrayList<>();
recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this.context);
recyclerView.setLayoutManager(linearLayoutManager);
//linearLayoutManager.setOrientation;
recyclerView.setLayoutManager(linearLayoutManager);
if (AppStatus.getInstance(this.context).isOnline(this.context)) {
new GetSpeakerList().execute(new Void[0]);
} else if (this.sessionContoller.getSpeakerData() != null) {
setData(this.sessionContoller.getSpeakerData());
} else {
Dialog.noInternetAlertBox(this.context);
}
// new GetSpeakerList().execute(new Void[0]);
recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this.context,new Listener()));
return myview;
}
class Listener implements RecyclerItemClickListener.ClickListener{
#Override
public void onItemClick(View view, int i) {
SpeakersBean speakersBean=SpeakersFrag.this.getSpeakerAdapter().getItem(i);
Intent in=new Intent(SpeakersFrag.this.context,SpeakerDetail.class);
in.putExtra("speaker", speakersBean);
startActivity(in);
}
}
class GetSpeakerList extends AsyncTask<Void, Void,String> {
ProgressDialog pd;
#Override
protected void onPreExecute() {
// pd = new ProgressDialog(getActivity()).show(getActivity(), "", "Loading...");
SpeakersFrag.this.progressDialog = new ProgressDialog(SpeakersFrag.this.context);
SpeakersFrag.this.progressDialog.setMessage("Loading...");
SpeakersFrag.this.progressDialog.setCancelable(false);
SpeakersFrag.this.progressDialog.show();
}
#Override
protected String doInBackground(Void... params) {
return SpeakersFrag.this.performPostCallback(Constants.Webservice.SPEAKER_API);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (!result.equals(BuildConfig.FLAVOR))
{
try
{
JSONObject jsonObject = new JSONObject(result); // set ` *emphasized text*`status code to continue the webservice as define in constants
if (jsonObject.getString("status_code").equals("100") && jsonObject.getString("message").equalsIgnoreCase("Success"))
{
System.out.println("Speaker data with Json and gson Parsing");
sessionContoller = new SessionContoller(getContext());
JSONArray jsonArray = jsonObject.getJSONArray("items"); //items
SpeakersFrag.this.dataset = (List) new Gson().fromJson(jsonArray.toString()
, new TypeToken<List<SpeakersBean>>() {}.getType());
SpeakersFrag.this.speakerAdapter = new SpeakerAdapter(SpeakersFrag.this.context, SpeakersFrag.this.dataset);
SpeakersFrag.this.recyclerView.setAdapter(SpeakersFrag.this.speakerAdapter);
SpeakersFrag.this.sessionContoller.setSpeakerData(jsonArray.toString());
}
} catch (JSONException e)
{
Log.e("SpeakerFragment", e.toString(), e);
// e.printStackTrace();
}
}
else if (SpeakersFrag.this.sessionContoller.getSpeakerData() != null) {
SpeakersFrag.this.setData(SpeakersFrag.this.sessionContoller.getSpeakerData());
}else{
Toast.makeText(getActivity(),Constants.SERVER_ERROR,Toast.LENGTH_LONG).show();
}
SpeakersFrag.dismissDialog(SpeakersFrag.this.progressDialog);
}
}
private void setData(String speakerData){
JSONException e;
try {
JSONArray jsonSpeaker = new JSONArray(speakerData);
JSONArray jarray;
{
try {
this.dataset = (List) new Gson().fromJson(jsonSpeaker.toString(), new TypeToken<TypeToken<List<SpeakersBean>>>(){}.getType());
this.speakerAdapter = new SpeakerAdapter(SpeakersFrag.this.context, SpeakersFrag.this.dataset);
this.recyclerView.setAdapter(this.speakerAdapter); //add speakerfrag
jarray=jsonSpeaker;
// ().getType());
} catch (Exception e1) {
jarray = jsonSpeaker;
e1.printStackTrace();
}
}
}catch (JSONException e3) {
e=e3;
e.printStackTrace();
}
}
public String performPostCallback(String requestURL)
{
String response=BuildConfig.FLAVOR;
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
//send post data request
HttpURLConnection connection=(HttpURLConnection) new URL(requestURL).openConnection();
connection.setReadTimeout(15000);
connection.setConnectTimeout(15000);
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setReadTimeout(15000);
OutputStream outputStream=connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8")); //UTF-8 encode the string into utf format
outputStream.flush(); //flushes the output stream and forces to any buffered device to be written out
outputStream.close(); //close pd
if (connection.getResponseCode() != ItemTouchHelper.Callback.DEFAULT_DRAG_ANIMATION_DURATION) {
return BuildConfig.FLAVOR;
}
//Read the server response
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while (true) {
String line = br.readLine(); //read server response
if (line == null) {
return response;
}
response = response + line; //Append response
System.out.println("Response request====>>>>>"+response); //response from server
}
} catch (Exception e) {
Log.e("SpeakerFragment", e.toString(), e);
return response;
}
}
public SpeakerAdapter getSpeakerAdapter(){
return this.speakerAdapter;
}
public static void dismissDialog(ProgressDialog pd) {
if (pd != null) {
try {
if (pd.isShowing()) {
pd.dismiss();
}
} catch (Exception e)
{
e.printStackTrace();
} catch (Throwable th){
th.printStackTrace();
}
}
}
----------
}
Blockquote
I think its from the server side error....
Toast.makeText(getActivity(),Constants.SERVER_ERROR,Toast.LENGTH_LONG).show();
This code is working,thats why its showing that error

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.

Android listview not getting populated with data

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

Categories

Resources