Before trying to get a row of data from a MySQL server, I used a column and managed to get that into a listView through tutorials. But for getting data in a row from a table, I couldn't manage to put it into a listView.
So what I'm trying to do is put "shift" from background worker into a listview.
PHP SQL query:
$sql = "SELECT id, employee, hours FROM selected_shifts WHERE day = '$day';";
Navigation drawer from Main Activity:
if (items[0].equals(mExpandableListTitle.get(groupPosition))) {
if (items[0].equals(mExpandableListTitle.get(childPosition))) {
String day = "Monday";
OnChoice(day);
} else if (items[1].equals(mExpandableListTitle.get(childPosition))) {
String day= "Tuesday";
OnChoice(day);
} else if (items[2].equals(mExpandableListTitle.get(childPosition))) {
String day = "Wednesday";
OnChoice(day);
} else if (items[3].equals(mExpandableListTitle.get(childPosition))) {
String day = "Thursday";
OnChoice(day);
} else if (items[4].equals(mExpandableListTitle.get(childPosition))) {
String day = "Friday";
OnChoice(day);
}
}
mDrawerLayout.closeDrawer(GravityCompat.START);
return false;
}
});
}
public void OnChoice(String day) {
String type = "choice";
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute(type, day);
}
Background worker(getting data from MySQL server):
public class BackgroundWorker extends AsyncTask<String,Void,String> {
Context context;
AlertDialog alertDialog;
BackgroundWorker (Context ctx) {
context = ctx;
}
#Override
protected String doInBackground(String... params) {
String type = params[0];
String shifts_url = "***PHP LINK***";
if(type.equals("choice")) {
try {
String day = params[1];
URL url = new URL(shifts_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("day","UTF-8")+"="+URLEncoder.encode(day,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String shift="";
String line="";
while((line = bufferedReader.readLine())!= null) {
shift += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return shift;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Status");
}
#Override
protected void onPostExecute(String shift) {
//Toast the data as json
Toast.makeText(context, shift, Toast.LENGTH_LONG).show();
}
#Override
protected void onProgressUpdate(Void... values)
{
super.onProgressUpdate(values);
}
}
EDIT
Putting it into ListView:
public void onTaskCompleted(String shift) {
try {
loadIntoListView(shift);
} catch (JSONException e) {
e.printStackTrace();
}
}
private void loadIntoListView(String shift) throws JSONException {
JSONArray jsonArray = new JSONArray(shift);
String[] list = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
list[i] = obj.getString(shift);
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
listView.setAdapter(arrayAdapter);
}
So what you want to do to pass the shift back is use a custom "Listener".
Create this
public interface TaskListener {
void onTaskCompleted(String shift);
}
And on your BackgroundWorker change the constructor as follow:
TaskListener taskListener;
BackgroundWorker(Context context, TaskListener taskListener){
this.context = context;
this.taskListener = taskListener;
}
Then on the onPostExecute method, do a taskListener.onTaskCompleted(shift).
When you call the BackgroundWorker constructor pass this as the second parameter:
BackgroundWorker backgroundWorker = new BackgroundWorker(this, this)
Then implement TaskListener on your Main and implement the method.
Something like this:
... MainActivity implements TaskListener
...
#override
onTaskCompleted(String shift) {
// You have your `shift` here to do with as you please
}
At your onPostExecute() you should add the "shift" to a dataSet in your adapter.
Related
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);
In my code i had caught data from a JSON file,
I executed the program, it stopped but didn't crash.
i've tried to change json file. I found one that is Smaller than the first one and so the program works.
this JSON file is made of data o premier legue(England) and contain 3 mainly data, the name, a key and a code of the squads.
public class MainActivity extends AppCompatActivity {
private ProgressDialog caric;
private String TAG = MainActivity.class.getSimpleName();
public ArrayMap<Integer, Valori> ArrayDati = new ArrayMap<>();
Button buttonProg;
TextView textViewProg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonProg = (Button) findViewById(R.id.button);
textViewProg = (TextView) findViewById(R.id.textView);
buttonProg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JsonCLASS().execute("https://raw.githubusercontent.com/openfootball/football.json/master/2015-16/en.1.clubs.json");
}
});
}
private class JsonCLASS extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
caric = new ProgressDialog(MainActivity.this);
caric.setMessage("Please wait");
caric.setCancelable(false);
caric.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 + "\n");
Log.d("Response: ", "> " + 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;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray Arr = new JSONArray(jsonObject.getString("clubs"));
for (int i = 0; i < Arr.length(); i++){
JSONObject jsonPart = Arr.getJSONObject(i);
ArrayDati.put(i,new Valori( jsonPart.getString("key"), jsonPart.getString("name"), jsonPart.getString("code")));
textViewProg.setText(textViewProg.getText()+"key : "+ ArrayDati.get(i).Key
+"\n"+textViewProg.getText()+"name : "+ ArrayDati.get(i).Name
+"\n"+textViewProg.getText()+"code : "+ ArrayDati.get(i).Code );
}
} catch (Exception e ){
e.printStackTrace();
}
if (caric.isShowing()) {
caric.dismiss();
}
}
}
}
And a class to pass the data
public class Valori {
String Key;
String Name;
String Code;
public Valori(String key, String name, String code) {
this.Key = key;
this.Name = name;
this.Code = code;
}
}
With this code the application stops but it doesn't close.
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.
I have a button that when used to run a asyntask class, I use it for set into a value in a textView. When he returns to the class that called the method, the value of the TextView caught and put in a Toast but the first time I click the Toast not appear any message, in the second works. What to do?
This is the method that calls the button
btnDadosPessoais.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String pega = TextAux.getText().toString();
Toast.makeText(getActivity(), pega, Toast.LENGTH_SHORT).show();
gravarDadoss(view);
}
});
TV is my TextView, I'm putting a simple string
protected void onPostExecute(String resposta) {
if(resposta.equals("Sem acesso à Internet")&&dialog.isShowing())
{
tv.setText(resposta);
dialog.dismiss();
}
else if (dialog.isShowing()) {
dialog.dismiss();
valida(resposta);
}
}
Asyntask here
`public class BackgroudCadPessoa extends AsyncTask {
ProgressDialog dialog;
Context ctx;
String pega;
ConnectivityManager connectivityManager;
TextView tv;
BackgroudCadPessoa(Context ctx, View v) {
this.ctx = ctx;
dialog = new ProgressDialog(ctx);
tv = (TextView) v.findViewById(R.id.textAux);
}
#Override
protected void onPreExecute() {
connectivityManager = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
dialog.setMessage("Aguarde...");
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setIndeterminate(true);
dialog.show();
}
#Override
protected String doInBackground(String... params) {
if (connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isAvailable() && connectivityManager.getActiveNetworkInfo().isConnected()) {
String urls = "my URL";
String nome = params[0];
try {
URL url = new URL(urls);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
//httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String data = URLEncoder.encode("nome", "UTF-8") + "=" + URLEncoder.encode(nome, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
String response = "";
String line = "";
while ((line = bufferedReader.readLine()) != null) {
response += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return response;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
return "Sem acesso à Internet";
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String resposta) {
if(resposta.equals("Sem acesso à Internet")&&dialog.isShowing())
{
tv.setText(resposta);
dialog.dismiss();
}
else if (dialog.isShowing()) {
dialog.dismiss();
valida(resposta);
}
}
public void valida(String js)
{
JSONArray jsonArray;
if (js.equals(null)) {
tv.setText("Erro ao Cadastrar");
} else {
try {
JSONObject jo = new JSONObject(js);
jsonArray = jo.getJSONArray("Resposta");
int count = 0;
while (count < jsonArray.length()) {
JSONObject jsonObject = jsonArray.getJSONObject(count);
pega = jsonObject.getString("resposta");
count++;
}
if (pega == null)
{
tv.setText("Erro ao Cadastrar");
}
else if (pega.equals("Dados Cadastrados"))
{
tv.setText("Dados Cadastrados");
}
else if (pega.equals("Erro ao Cadastrar"))
{
tv.setText("Erro ao Cadastrar");
}
else
{
tv.setText("Dados Cadastrados");
}
} catch (JSONException ex) {
ex.printStackTrace();
}
}
}
}
`
You want your Toast to appear AFTER your AsyncTask finishes its output to TextAux?
Then you need to put your toaster in the onPostExecute
#Override
protected void onPostExecute(String resposta) {
if(resposta.equals("Sem acesso à Internet")&&dialog.isShowing())
{
tv.setText(resposta);
dialog.dismiss();
Toast.makeText(getActivity(), resposta, Toast.LENGTH_SHORT).show();
}
else if (dialog.isShowing()) {
dialog.dismiss();
valida(resposta);
}
}
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.