I am developing a MovieApp which loads movie posters in MainActivity Fragment using AsyncTask background thread. I am using gridview and BaseAdapter to display images. Following is the code.
MainActivityFragment.java :
package com.android.example.cinemaapp.app;
import android.app.Fragment;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
public class MainActivityFragment extends Fragment{
MoviePosterAdapter moviePosterAdapter;
GridView posterGridView;
public HashMap<String, JSONObject> movieMap;
public MainActivityFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onStart(){
super.onStart();
updateMovies();
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.moviefragment, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_refresh) {
updateMovies();
}
return super.onOptionsItemSelected(item);
}
public void updateMovies(){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
String sortBy = sharedPreferences.getString(getString(R.string.pref_sort_key), getString(R.string.pref_sort_popular));
new FetchMoviePosterTask().execute(sortBy);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
moviePosterAdapter = new MoviePosterAdapter(getActivity());
posterGridView = (GridView) rootView.findViewById(R.id.gridview_movie);
posterGridView.setAdapter(moviePosterAdapter);
posterGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
// logic to start detail activity
startActivity(intent);
}
});
return rootView;
}
public class FetchMoviePosterTask extends AsyncTask<String, String, Void> implements Serializable {
#Override
protected Void doInBackground(String... params) {
Log.v("FetchMoviePosterTask", "In background method");
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String movieJsonStr;
try {
//logic to create uri builder
URL url = new URL(builtUri.toString());
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.
movieJsonStr = null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
movieJsonStr = null;
}
movieJsonStr = buffer.toString();
// Log.v("MainActivityFragment", "Movie json "+movieJsonStr);
try {
String[] posterPaths = getPosterPaths(movieJsonStr);
for(String path : posterPaths){
publishProgress(path);
}
}catch(JSONException je){
Log.e("MoviePosterPath","Error while parsing JSON");
}
} catch (IOException e) {
Log.e("MoviePosterAdapter", "Error ", e);
movieJsonStr = null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("MoviePosterAdapter", "Error closing stream", e);
}
}
}
return null;
}
public String[] getPosterPaths(String movieJsonStr) throws JSONException{
final String POSTER_PATH = //some value
final String POSTER_SIZE = //some value
JSONObject jsonObject = new JSONObject(movieJsonStr);
JSONArray results = jsonObject.getJSONArray("results");
String[] posterStrs = new String[results.length()];
movieMap = new HashMap<String, JSONObject>();
for(int i =0; i < results.length(); i++){
JSONObject movieObj = (JSONObject) results.get(i);
posterStrs[i] = POSTER_PATH + POSTER_SIZE + movieObj.getString("poster_path");
movieMap.put(posterStrs[i], movieObj);
}
return posterStrs;
}
#Override
protected void onProgressUpdate(String... posterValues){
Log.v("FetchMoviePosterTask", "In onProgress method");
moviePosterAdapter.add(posterValues[0]);
super.onProgressUpdate(posterValues);
}
#Override
protected void onPostExecute(Void result) {
Log.v("FetchMoviePosterTask", "In onPostExecute method");
moviePosterAdapter.notifyDataSetChanged();
super.onPostExecute(result);
}
}
}
MoviePosterAdapter.java :
package com.android.example.cinemaapp.app;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class MoviePosterAdapter extends BaseAdapter {
ArrayList<String> movieArray = new ArrayList<String>();
private Context mContext;
public MoviePosterAdapter(Context c) {
mContext = c;
}
void add(String path){
movieArray.add(path);
}
void clear(){
movieArray.clear();
}
void remove(int index){
movieArray.remove(index);
}
#Override
public int getCount() {
return movieArray.size();
}
#Override
public Object getItem(int position) {
return movieArray.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
// if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
} else {
imageView = (ImageView) convertView;
}
Picasso.with(mContext).load(movieArray.get(position)).into(imageView);
return imageView;
}
}
Problem : When the application is first launched, UI is not getting populated with imageviews. In Logcat I could see control is flowing through doBackground(), onProgressUpdate() and onPostExecute().
When I click 'Refresh' button or If i navigate to some other activity or app and return to Movie app UI (onResume()) it is working perfectly fine. Images are displayed.
Many thanks in advance!
You should change updateMovies(); from onStart() to onCreateView. As Gabe Sechan said, you're wrong about the lifecycle. Try to do some research on the Fragment lifecycle.
Just you need to call method updateMovies(); from onCreateView() after posterGridView = (GridView) rootView.findViewById(R.id.gridview_movie);
remove call from start();
Related
I have an MainActivity that in turn has several fragments.
In the fragments builder I get an Activity ...
I have a GETJson method that is responsible for all my http requests. This needs to return a JSONObject to the caller.
The method uses AsynkTask, so I created an interface and implement the fragments to get the return from OnPostExecute.
However as all fragments share the same activity (MainActivity) always returns there.
package JSON;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.example.piadas.MainActivity;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import utils.OnJsonFinished;
public class GetJson extends AsyncTask<String, Void, String> {
public interface OnJsonFinished{
public void onJsonFinishedMethod(Activity act, Context ctx, String response);
}
ProgressDialog dialog;
Context ctx;
Activity act;
String msg;
private utils.OnJsonFinished listener;
public GetJson(Context ctx, Activity act) {
this.ctx = ctx;
this.act = act;
if(act instanceof utils.OnJsonFinished){
this.listener = (utils.OnJsonFinished)act;
}
else{
throw new ClassCastException(act.toString()
+ " must implement OnJsonFinished");
}
}
protected void onPreExecute() {
super.onPreExecute();
dialog = ProgressDialog.show(ctx, "Aguarde", "Consultando...");
}
#Override
protected String doInBackground(String... strings) {
String command = strings[0];
try {
URL url = new URL(command);
URLConnection con = url.openConnection();
con.setRequestProperty("Authorization", "Basic c3VwZXI6MTIzNA==");
con.setConnectTimeout(60000);
//con.setReadTimeout(readTimeout);
InputStream is = con.getInputStream();
/*HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(command);
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 8000);
client = new DefaultHttpClient(httpParams);
request.addHeader("Authorization", "Basic c3VwZXI6MTIzNA==");
HttpResponse response = client.execute(request);
InputStream is = response.getEntity().getContent();*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
msg = "Efetuado com sucesso!";
//PrincipalActivity.PDV.setConectado(true);
return sb.toString();
} catch (Exception ex) {
Log.e("Erro", "Descrição:", ex);
msg = ex.toString();
return "";
}
}
protected void onPostExecute(String json) {
dialog.dismiss();
if (json.equals("")) {
Toast.makeText(ctx, msg, Toast.LENGTH_SHORT).show();
}
else{
listener.onJsonFinishedMethod(act, ctx, json);
}
}
}
package utils;
import android.app.Activity;
import android.content.Context;
public interface OnJsonFinished {
public void onJsonFinishedMethod(Activity act, Context ctx, String response);
}
package com.example.piadas;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import JSON.GetJson;
import JSON.apiPiadas;
import adapter.adapterListPiadas;
import piadas.entidade.Categoria;
import piadas.entidade.FaixaEtaria;
import piadas.entidade.Piada;
import utils.OnJsonFinished;
public class BancoPiadaFragment extends Fragment implements OnJsonFinished {
RadioGroup rgCategoria;
RadioGroup rgFaixa;
private View view;
Button btnBuscar;
EditText editPalavra;
List<Piada> listaPiadas;
ListView lvPiadas;
Context ctx;
Activity act;
adapterListPiadas adapterPiadas;
public BancoPiadaFragment(Activity act, Context ctx) {
this.ctx = ctx;
this.act = act;
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_bancopiada, container, false);
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initView();
init();
}
private void initView(){
btnBuscar = view.findViewById(R.id.btnBuscar);
rgCategoria = view.findViewById(R.id.gpCateg);
rgFaixa = view.findViewById(R.id.gpFaixas);
editPalavra = view.findViewById(R.id.editPalavra);
lvPiadas = view.findViewById(R.id.lvPiadas);
}
private void init(){
btnBusca_click();
//listaPiadas = new ArrayList<>();
lvPiadas.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
FragmentManager fm = getActivity().getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.fragment_content, new PiadaFragment(listaPiadas.get(position))).addToBackStack(null);
ft.commit();
}
});
}
private void btnBusca_click(){
btnBuscar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listaPiadas = new ArrayList<>();
aplicaFiltroPiadas();
}
});
}
private void aplicaFiltroPiadas(){
//int i = rgCategoria.getCheckedRadioButtonId();
int categoria = -1;
int faixaEtaria = -1;
String palavra = "";
switch (rgCategoria.getCheckedRadioButtonId()) {
case R.id.rbTCategoria:
categoria = -1;
break;
case R.id.rbJoaozinho:
categoria = 2;
break;
case R.id.rbJapones:
categoria = 3;
break;
case R.id.rbLoira:
categoria = 0;
break;
case R.id.rbPortugues:
categoria = 1;
break;
}
switch (rgFaixa.getCheckedRadioButtonId()) {
case R.id.rbTFaixas:
faixaEtaria = -1;
break;
case R.id.rbFLivre:
faixaEtaria = 0;
break;
case R.id.rbF14:
faixaEtaria = 1;
break;
case R.id.rbF18:
faixaEtaria = 2;
break;
}
palavra = editPalavra.getText().toString().trim();
findPiadas(categoria, faixaEtaria, palavra);
//Toast.makeText(this, "Teste:", Toast.LENGTH_SHORT).show();
}
private void findPiadas(int categoria, int faixa, String palavra){
new GetJson(ctx, act).execute(apiPiadas.findPiada(categoria, faixa, palavra));
}
private void preparaTela(Activity act){
adapterPiadas = new adapterListPiadas(listaPiadas, act);
lvPiadas.setAdapter(adapterPiadas);
}
#Override
public void onJsonFinishedMethod(Activity act, Context ctx, String response) {
if (!response.equals("")) {
try{
JSONArray arrayPiadas = new JSONArray(response);
JSONObject objPiada;
for(int i=0; i < arrayPiadas.length(); i++){
objPiada = arrayPiadas.getJSONObject(i);
JSONObject objCategoria = objPiada.getJSONObject("categoria");
JSONObject objFaixaEtaria = objPiada.getJSONObject("faixaEtaria");
Categoria cat = new Categoria(objCategoria.getInt("id"), objCategoria.getString("nome"));
FaixaEtaria faixaEtaria = new FaixaEtaria(objFaixaEtaria.getInt("id"), objFaixaEtaria.getString("descricao"));
listaPiadas.add(new Piada(objPiada.getInt("id"), objPiada.getString("titulo"), cat, faixaEtaria, objPiada.getString("conteudo"), objPiada.getString("imagem")));
}
preparaTela(act);
}catch(Exception ex){
Toast.makeText(ctx, ex.toString(), Toast.LENGTH_SHORT).show();
}
}
}
}
I need to identify which fragment called GETJson and return the String to it.
If you want to each fragment to get their own network callback, you SHOULD pass fragments to GetJson as listener, rather than Activity.
Modify GetJson's constructor:
public GetJson(Activity act, OnJsonFinished listener) {
}
just use act as context, no need to pass both them.
In BancoPiadaFragment:
private void findPiadas(int categoria, int faixa, String palavra){
new GetJson(act, this).execute(apiPiadas.findPiada(categoria, faixa, palavra));
}
#nonnull error at inflater , any one can solve this error?
im new to android i don't know how to solve this error any solution ?
is it the error of due theme or something else ,do my code have some major issue ?? can you solve this error please. due to this error my code is not working. your help will be highly appreciated
my import in the code is listed below
import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.app.DownloadManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.support.v7.widget.DividerItemDecoration;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
import android.support.annotation.Nullable;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import static android.content.Context.DOWNLOAD_SERVICE;
import java.lang.reflect.Type;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.ref.WeakReference;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class FilesListingFragment extends android.support.v4.app.Fragment {
private static final String TAG = "FilesListingFragment";
public static final String PATH_FILES = "http://%s:%s/files";
public static final String PATH_STATUS = "http://%s:%s/status";
public static final String PATH_FILE_DOWNLOAD = "http://%s:%s/file/%s";
private String mSenderIp = null, mSenderSSID;
private ContactSenderAPITask mUrlsTask;
private ContactSenderAPITask mStatusCheckTask;
private String mPort, mSenderName;
static final int CHECK_SENDER_STATUS = 100;
static final int SENDER_DATA_FETCH = 101;
RecyclerView file;
ProgressBar progressBar;
TextView mTextView;
private SenderFilesListingAdapter mFilesAdapter;
private UiUpdateHandler uiUpdateHandler;
private static final int SENDER_DATA_FETCH_RETRY_LIMIT = 3;
private int senderDownloadsFetchRetry = SENDER_DATA_FETCH_RETRY_LIMIT, senderStatusCheckRetryLimit = SENDER_DATA_FETCH_RETRY_LIMIT;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_files_listing, null);
file = (RecyclerView) v.findViewById(R.id.files_list);
progressBar = (ProgressBar) v.findViewById(R.id.loading);
mTextView = (TextView) v.findViewById(R.id.empty_listing_text);
mTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mTextView.setVisibility(View.GONE);
progressBar.setVisibility(View.VISIBLE);
fetchSenderFiles();
}
});
file.setLayoutManager(new LinearLayoutManager(getActivity()));
file.addItemDecoration(new DividerItemDecoration(getResources().getDrawable(R.drawable.lidivider)));/**here is the error */
mFilesAdapter = new SenderFilesListingAdapter(new ArrayList<String>());
file.setAdapter(mFilesAdapter);
uiUpdateHandler = new UiUpdateHandler(this);
return v;
}
public static FilesListingFragment getInstance(String senderIp, String ssid, String senderName, String port) {
FilesListingFragment fragment = new FilesListingFragment();
Bundle data = new Bundle();
data.putString("senderIp", senderIp);
data.putString("ssid", ssid);
data.putString("name", senderName);
data.putString("port", port);
fragment.setArguments(data);
return fragment;
}
#Override
public void onAttach(Context activity) {
super.onAttach(activity);
if (null != getArguments()) {
mSenderIp = getArguments().getString("senderIp");
mSenderSSID = getArguments().getString("ssid");
mPort = getArguments().getString("port");
mSenderName = getArguments().getString("name");
Log.d(TAG, "sender ip: " + mSenderIp);
}
}
#Override
public void onResume() {
super.onResume();
fetchSenderFiles();
checkSenderAPIAvailablity();
}
private void fetchSenderFiles() {
progressBar.setVisibility(View.VISIBLE);
if (null != mUrlsTask)
mUrlsTask.cancel(true);
mUrlsTask = new ContactSenderAPITask(SENDER_DATA_FETCH);
mUrlsTask.execute(String.format(PATH_FILES, mSenderIp, mPort));
}
private void checkSenderAPIAvailablity() {
if (null != mStatusCheckTask)
mStatusCheckTask.cancel(true);
mStatusCheckTask = new ContactSenderAPITask(CHECK_SENDER_STATUS);
mStatusCheckTask.execute(String.format(PATH_STATUS, mSenderIp, mPort));
}
#Override
public void onPause() {
super.onPause();
if (null != mUrlsTask)
mUrlsTask.cancel(true);
}
#Override
public void onDestroy() {
super.onDestroy();
if (null != uiUpdateHandler)
uiUpdateHandler.removeCallbacksAndMessages(null);
if (null != mStatusCheckTask)
mStatusCheckTask.cancel(true);
}
public String getSenderSSID() {
return mSenderSSID;
}
public String getSenderIp() {
return mSenderIp;
}
private void loadListing(String contentAsString) {
Type collectionType = new TypeToken<List<String>>() {
}.getType();
ArrayList<String> files = new Gson().fromJson(contentAsString, collectionType);
progressBar.setVisibility(View.GONE);
if (null == files || files.size() == 0) {
mTextView.setText("No Downloads found.\n Tap to Retry");
mTextView.setVisibility(View.VISIBLE);
} else {
mTextView.setVisibility(View.GONE);
mFilesAdapter.updateData(files);
}
}
private void onDataFetchError() {
progressBar.setVisibility(View.GONE);
mTextView.setVisibility(View.VISIBLE);
mTextView.setText("Error occurred while fetching data.\n Tap to Retry");
}
private long postDownloadRequestToDM(Uri uri, String fileName) {
// Create request for android download manager
DownloadManager downloadManager = (DownloadManager) getActivity().getSystemService(DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setTitle(fileName);
request.setDescription("ShareThem");
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalFilesDir(getActivity(),
Environment.DIRECTORY_DOWNLOADS, fileName);
return downloadManager.enqueue(request);
}
private class SenderFilesListingAdapter extends RecyclerViewArrayAdapter<String, SenderFilesListItemHolder> {
SenderFilesListingAdapter(List<String> objects) {
super(objects);
}
void updateData(List<String> objects) {
clear();
mObjects = objects;
notifyDataSetChanged();
}
#Override
public SenderFilesListItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).
inflate(R.layout.listitem_file, parent, false);
return new SenderFilesListItemHolder(itemView);
}
#Override
public void onBindViewHolder(SenderFilesListItemHolder holder, int position) {
final String senderFile = mObjects.get(position);
holder.itemView.setTag(senderFile);
final String fileName = senderFile.substring(senderFile.lastIndexOf('/') + 1, senderFile.length());
holder.title.setText(fileName);
holder.download.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
postDownloadRequestToDM(Uri.parse(String.format(PATH_FILE_DOWNLOAD, mSenderIp, mPort, mObjects.indexOf(senderFile))), fileName);
Toast.makeText(getActivity(), "Downloading " + fileName + "...", Toast.LENGTH_SHORT).show();
}
});
}
}
static class SenderFilesListItemHolder extends RecyclerView.ViewHolder {
TextView title;
ImageButton download;
SenderFilesListItemHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.sender_list_item_name);
download = (ImageButton) itemView.findViewById(R.id.sender_list_start_download);
}
}
/**
* Performs network calls to fetch data/status from Sender.
* Retries on error for times bases on values of {#link FilesListingFragment#senderDownloadsFetchRetry}
*/
private class ContactSenderAPITask extends AsyncTask<String, Void, String> {
int mode;
boolean error;
ContactSenderAPITask(int mode) {
this.mode = mode;
}
#Override
protected String doInBackground(String... urls) {
error = false;
try {
return downloadDataFromSender(urls[0]);
} catch (IOException e) {
e.printStackTrace();
error = true;
Log.e(TAG, "Exception: " + e.getMessage());
return null;
}
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
switch (mode) {
case SENDER_DATA_FETCH:
if (error) {
if (senderDownloadsFetchRetry >= 0) {
--senderDownloadsFetchRetry;
if (getView() == null || getActivity() == null || null == uiUpdateHandler)
return;
uiUpdateHandler.removeMessages(SENDER_DATA_FETCH);
uiUpdateHandler.sendMessageDelayed(uiUpdateHandler.obtainMessage(mode), 800);
return;
} else senderDownloadsFetchRetry = SENDER_DATA_FETCH_RETRY_LIMIT;
if (null != getView())
onDataFetchError();
} else if (null != getView())
loadListing(result);
else Log.e(TAG, "fragment may have been removed, File fetch");
break;
case CHECK_SENDER_STATUS:
if (error) {
if (senderStatusCheckRetryLimit > 1) {
--senderStatusCheckRetryLimit;
uiUpdateHandler.removeMessages(CHECK_SENDER_STATUS);
uiUpdateHandler.sendMessageDelayed(uiUpdateHandler.obtainMessage(CHECK_SENDER_STATUS), 800);
} else if (getActivity() instanceof ReceiverActivity) {
senderStatusCheckRetryLimit = SENDER_DATA_FETCH_RETRY_LIMIT;
((ReceiverActivity) getActivity()).resetSenderSearch();
Toast.makeText(getActivity(), getString(R.string.p2p_receiver_error_sender_disconnected), Toast.LENGTH_SHORT).show();
} else
Log.e(TAG, "Activity is not instance of ReceiverActivity");
} else if (null != getView()) {
senderStatusCheckRetryLimit = SENDER_DATA_FETCH_RETRY_LIMIT;
uiUpdateHandler.removeMessages(CHECK_SENDER_STATUS);
uiUpdateHandler.sendMessageDelayed(uiUpdateHandler.obtainMessage(CHECK_SENDER_STATUS), 1000);
} else
Log.e(TAG, "fragment may have been removed: Sender api check");
break;
}
}
private String downloadDataFromSender(String apiUrl) throws IOException {
InputStream is = null;
try {
URL url = new URL(apiUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
int response =
conn.getResponseCode();
Log.d(TAG, "The response is: " + response);
is = conn.getInputStream();
// Convert the InputStream into a string
return readIt(is);
} finally {
if (is != null) {
is.close();
}
}
}
private String readIt(InputStream stream) throws IOException {
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(
new InputStreamReader(stream, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
stream.close();
}
return writer.toString();
}
}
private static class UiUpdateHandler extends Handler {
WeakReference<FilesListingFragment> mFragment;
UiUpdateHandler(FilesListingFragment fragment) {
mFragment = new WeakReference<>(fragment);
}
#Override
public void handleMessage(Message msg) {
FilesListingFragment fragment = mFragment.get();
if (null == mFragment)
return;
switch (msg.what) {
case CHECK_SENDER_STATUS:
fragment.checkSenderAPIAvailablity();
break;
case SENDER_DATA_FETCH:
fragment.fetchSenderFiles();
break;
}
}
}
fragment_files_listing
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
tools:context=".receiver.FilesListingFragment"
>
<android.support.v7.widget.RecyclerView
android:id="#+id/files_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical" />
<ProgressBar xmlns:android="http://schemas.android.com/apk/res/android"
style="#android:style/Widget.Holo.ProgressBar"
android:layout_width="wrap_content"
android:id="#+id/loading"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_gravity="center" />
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/empty_listing_text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
android:clickable="true"
android:gravity="center"
android:text="No Downloads found.\n Tap to Retry"
android:visibility="gone" />
</RelativeLayout>
Not annotated parameter overrides #NonNull parameter
This is just a warning. You have
#Override
public View onCreateView(LayoutInflater inflater...
while the base class you're extending has nullity annotation on the inflater parameter.
public View onCreateView(#NonNull LayoutInflater inflater...
You can just alt-enter in Android Studio to get a quick fix menu that has the option to add the missing annotation there.
due to this error my code is not working.
Missing an annotation like that just causes a warning. The reason for "not working" is something else. Please start by updating your question and specifying what "not working" means to you here.
Try to change this line
View v = inflater.inflate(R.layout.fragment_files_listing, null);
to
View v = inflater.inflate(R.layout.fragment_files_listing, container, false);
This will inflate your layout with your fragment container.
You have to change this line
View v = inflater.inflate(R.layout.fragment_files_listing, null);
to
View v = inflater.inflate(R.layout.fragment_files_listing, container, false);
and then clean your project and invalidate cache restart you android studio.
I created an app which shows data from json object from web to my movie list view.
The error is that it says there is
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference.
Here is my full code that i have taken to load the movie parameters from web and display it as list.
MainActivity.java
package com.example.shailendra.jsonmovies;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import model.MovieModel;
public class MainActivity extends AppCompatActivity {
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView=(ListView)findViewById(R.id.listView);
// new JsonTask().execute("http://jsonparsing.parseapp.com/jsonData/moviesDemoList.txt");
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
public class JsonTask extends AsyncTask<String,String,List<MovieModel>>
{ MovieAdapter adapter=null;
#Override
protected void onPostExecute(List<MovieModel> s) {
try{
super.onPostExecute(s);
adapter= new MovieAdapter(getApplicationContext(),R.layout.row,s);
listView.setAdapter(adapter);}
catch (Exception e)
{
e.printStackTrace();
}
}
#Override
protected List<MovieModel> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url= new URL(params[0]);
connection=(HttpURLConnection)url.openConnection();
connection.connect();
InputStream is= connection.getInputStream();
InputStreamReader isr= new InputStreamReader(is);
reader= new BufferedReader(isr);
StringBuffer buffer= new StringBuffer();
String line=null;
while ((line=reader.readLine())!=null)
{
buffer.append(line);
}
String finalJson= buffer.toString();
JSONObject parentObject= new JSONObject(finalJson);
JSONArray parentArray= parentObject.getJSONArray("movies");
List<MovieModel> movieModelList = new ArrayList<>();
MovieModel movieModel= new MovieModel();
for(int i=0;i<parentArray.length();i++)
{
JSONObject finalObject= parentArray.getJSONObject(i);
String movieName= finalObject.getString("movie");
movieModel.setMovie(finalObject.getString("movie"));
int year= finalObject.getInt("year");
movieModel.setYear(finalObject.getInt("year"));
movieModel.setRating((float)finalObject.getDouble("year"));
movieModel.setDirector(finalObject.getString("director"));
movieModel.setDuration(finalObject.getString("duration"));
movieModel.setTaglline(finalObject.getString("tagline"));
movieModel.setStory(finalObject.getString("story"));
movieModel.setImage(finalObject.getString("image"));
List<MovieModel.Cast> castList = new ArrayList<>();
for(int j=0;j<finalObject.getJSONArray("cast").length();j++)
{
JSONObject castObject= finalObject.getJSONArray("cast").getJSONObject(j);
MovieModel.Cast cast= new MovieModel.Cast();
cast.setName(castObject.getString("name"));
castList.add(cast);
} movieModel.setCastList(castList);
movieModelList.add(movieModel);
}
return movieModelList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if(connection!=null)
{
connection.disconnect();}
try {
if(reader!=null)
{
reader.close();}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
new JsonTask().execute("http://jsonparsing.parseapp.com/jsonData/moviesDemoList.txt");
return true;
}
return super.onOptionsItemSelected(item);
}
}
movieAdapter.java
package com.example.shailendra.jsonmovies;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import java.util.List;
import model.MovieModel;
/**
* Created by Shailendra on 10/21/2016.
*/
public class MovieAdapter extends ArrayAdapter{
public List<MovieModel> movieModelList;
int resource;
LayoutInflater inflater;
public MovieAdapter(Context context, int resource, List<MovieModel> objects) {
super(context, resource, objects);
movieModelList=objects;
this.resource=resource;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
inflater=LayoutInflater.from(getContext());
View customView=inflater.inflate(R.layout.row,parent,false);
ImageView ivMovieIcon=(ImageView)customView.findViewById(R.id.ivIcon);
TextView tvMovie=(TextView)customView.findViewById(R.id.tvMovie);
TextView tvTagLine=(TextView)customView.findViewById(R.id.tvTagline);
TextView tvYear=(TextView)customView.findViewById(R.id.tvYear);
TextView tvDuration=(TextView)customView.findViewById(R.id.tvDuration);
TextView tvDirector=(TextView)customView.findViewById(R.id.tvDirector);
TextView tvCast=(TextView)customView.findViewById(R.id.tvCast);
TextView tvStory=(TextView)customView.findViewById(R.id.tvStory);
RatingBar ratingBare=(RatingBar) customView.findViewById(R.id.ratingBar);
tvMovie.setText(movieModelList.get(position).getMovie());
tvTagLine.setText(movieModelList.get(position).getTaglline());
tvYear.setText("Year: "+movieModelList.get(position).getYear());
tvDuration.setText(movieModelList.get(position).getDuration());
tvDirector.setText(movieModelList.get(position).getDirector());
StringBuffer stringBuffer= new StringBuffer();
for(MovieModel.Cast cast:movieModelList.get(position).getCastList())
{
stringBuffer.append(cast.getName() +", ");}
tvCast.setText(stringBuffer);
tvStory.setText(movieModelList.get(position).getStory());
ratingBare.setRating(movieModelList.get(position).getRating()/2);
return customView;
}
}
MovieModel.java
package model;
import java.util.List;
/**
* Created by Shailendra on 10/21/2016.
*/
public class MovieModel {
private String movie;
private int year;
private float rating;
private String duration;
private String director;
private String taglline;
private String image;
private String story;
private List<Cast> castList;
public static class Cast {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public String getMovie() {
return movie;
}
public void setMovie(String movie) {
this.movie = movie;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public float getRating() {
return rating;
}
public void setRating(float rating) {
this.rating = rating;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
public String getTaglline() {
return taglline;
}
public void setTaglline(String taglline) {
this.taglline = taglline;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getStory() {
return story;
}
public void setStory(String story) {
this.story = story;
}
public List<Cast> getCastList() {
return castList;
}
public void setCastList(List<Cast> castList) {
this.castList = castList;
}
}
Check out the json link if it is correct and you can check the format if json is correct or not in www.jsonlint.com
---> point 1)
Have to kept method getCount?
put get Count and see what it returns
#Override
public int getCount() {
if (movieModelList == null)
return (0);
movieModelList.size();
}
For array just define it globally
--->point 2
After your app starts working you may get white text as if text is behind your current layout. For that use getBaseContext(); instead of getApplicationContext();
In your adapter class override getCount() method
#Override
public int getCount() {
if (movieModelList == null)
return 0;
movieModelList.size()
}
Also check what value is returned from AsyncTask's doInBackground().
First of all define your MovieModel to global. and then Initialize it before you set adapter to your ListView. in your case you are not intialize your ArrayList.
do this way.
global declaration :
private ArrayList<MovieModel> movieModel;
and then inside your OnCreate method intialize it.
movie = new ArrayList<MovieModel>();
Example :
see this example :
http://androidexample.com/How_To_Create_A_Custom_Listview_-_Android_Example/index.php?view=article_discription&aid=67
I'm a high school student working for a magazine in South Korea known as Teen 10 Magazine. As an aspiring computer science major, I decided to make an RSS reader app for my magazine in order to showcase my skills for college applications (and also to create an app, which has always been my interest). Basically, I want to format my app to be similar to your typical news app (ex. CNN, BBC, etc).
Category Screen
In a DrawerLayout (as seen in the Category Screen), I decided to make a tab for each different category (such as News, Features, Entertainment, etc), including the Home category, which is where the categories the articles are under don't matter. When users click on each different tab, it gives them a list of articles that are categorized under that category. In order to get this data, I'm parsing the data to get the title (which is displayed in the list) and the link (which is set to an Intent so that users can access the article in the Web when it is clicked)
However, while some of the categories do work (Home, Lifestyle, Fashion), the rest of the categories are stuck in the loading screen for almost an infinite amount of time.
Example of loading category
I'm pretty sure that the codes of the categories that work and the categories that don't are the same (for reference, I copied and pasted and adjusted each different category accordingly, which could also be an issue but I'm not sure), and are getting their data from the appropriate sites.
Is it perhaps there are too many parsers (RssParser does the actual parsing and seven different "RssService"s use the parser to parse the data from each different category) for my app to work with? My app does seem to crash once in a while though...
I will post my codes below:
MainActivity.java:
package com.hfad.teen10magazine;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v7.app.ActionBarDrawerToggle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ShareActionProvider;
import android.support.v4.widget.DrawerLayout;
public class MainActivity extends Activity {
/* adds the fragment to the activity */
private ShareActionProvider shareActionProvider;
private String[] titles;
private ListView drawerList;
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle drawerToggle;
private int currentPosition = 0;
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Code to run when an item in the navigation drawer gets clicked
selectItem(position);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
titles = getResources().getStringArray(R.array.titles);
drawerList = (ListView)findViewById(R.id.drawer);
drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
//Initialize the ListView
drawerList.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_activated_1, titles));
drawerList.setOnItemClickListener(new DrawerItemClickListener());
//Display the correct fragment.
if (savedInstanceState != null) {
currentPosition = savedInstanceState.getInt("position");
setActionBarTitle(currentPosition);
} else {
selectItem(0);
}
//Create the ActionBarDrawerToggle
drawerToggle = new ActionBarDrawerToggle(this, drawerLayout,
R.string.open_drawer, R.string.close_drawer) {
//Called when a drawer has settled in a completely closed state
#Override
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
invalidateOptionsMenu();
}
//Called when a drawer has settled in a completely open state.
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu();
}
};
drawerLayout.addDrawerListener(drawerToggle);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
getFragmentManager().addOnBackStackChangedListener(
new FragmentManager.OnBackStackChangedListener() {
public void onBackStackChanged() {
FragmentManager fragMan = getFragmentManager();
Fragment fragment = fragMan.findFragmentByTag("visible_fragment");
if (fragment instanceof TopFragment) {
currentPosition = 0;
}
if (fragment instanceof LifestyleFragment) {
currentPosition = 1;
}
if (fragment instanceof EntFragment) {
currentPosition = 2;
}
if (fragment instanceof NewsFragment) {
currentPosition = 3;
}
if (fragment instanceof FeaturesFragment) {
currentPosition = 4;
}
if (fragment instanceof AcademicsFragment) {
currentPosition = 5;
}
if (fragment instanceof FashionFragment) {
currentPosition = 6;
}
setActionBarTitle(currentPosition);
drawerList.setItemChecked(currentPosition, true);
}
}
);
}
private void selectItem(int position) {
// update the main content by replacing fragments
currentPosition = position;
Fragment fragment;
switch(position) {
case 1:
fragment = new LifestyleFragment();
break;
case 2:
fragment = new EntFragment();
break;
case 3:
fragment = new NewsFragment();
break;
case 4:
fragment = new FeaturesFragment();
break;
case 5:
fragment = new AcademicsFragment();
break;
case 6:
fragment = new FashionFragment();
break;
default:
fragment = new TopFragment();
}
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragment_container, fragment, "visible_fragment");
ft.addToBackStack(null);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
//Set the action bar title
setActionBarTitle(position);
//Close the drawer
drawerLayout.closeDrawer(drawerList);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the drawer is open, hide action items related to the content view
boolean drawerOpen = drawerLayout.isDrawerOpen(drawerList);
menu.findItem(R.id.action_share).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("position", currentPosition);
}
private void setActionBarTitle(int position) {
String title="";
titles=getResources().getStringArray(R.array.titles);
if (position == 0){
title = getResources().getString(R.string.app_name);
} else {
title = titles[position];
}
getActionBar().setTitle(title);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
MenuItem menuItem = menu.findItem(R.id.action_share);
shareActionProvider = (ShareActionProvider) menuItem.getActionProvider();
setIntent("This is example text");
return super.onCreateOptionsMenu(menu);
}
private void setIntent(String text) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, text);
shareActionProvider.setShareIntent(intent);
}
}
RssItem.java:
package com.hfad.teen10magazine;
public class RssItem {
private final String title;
private final String link;
private final String pubDate;
public RssItem(String title, String link, String pubDate) {
this.title = title;
this.link = link;
this.pubDate = pubDate;
}
public String getTitle() {
return title;
}
public String getLink() {
return link;
}
public String getDate() {
return pubDate;
}
}
RssParser.java:
package com.hfad.teen10magazine;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.util.Xml;
public class RssParser {
// We don't use namespaces
private final String ns = null;
public List<RssItem> parse(InputStream inputStream) throws XmlPullParserException, IOException {
try {
XmlPullParser parser = Xml.newPullParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(inputStream, null);
parser.nextTag();
return readFeed(parser);
} finally {
inputStream.close();
}
}
private List<RssItem> readFeed(XmlPullParser parser) throws XmlPullParserException, IOException {
parser.require(XmlPullParser.START_TAG, null, "rss");
String title = null;
String link = null;
String pubDate = null;
List<RssItem> items = new ArrayList<RssItem>();
while (parser.next() != XmlPullParser.END_DOCUMENT) {
if (parser.getEventType() != XmlPullParser.START_TAG) {
continue;
}
String name = parser.getName();
if (name.equals("title")) {
title = readTitle(parser);
} else if (name.equals("link")) {
link = readLink(parser);
} else if (name.equals("pubDate")) {
pubDate = readDate(parser);
}
if (title != null && link != null && pubDate != null) {
RssItem item = new RssItem(title, link, pubDate);
items.add(item);
title = null;
link = null;
pubDate = null;
}
}
return items;
}
private String readLink(XmlPullParser parser) throws XmlPullParserException, IOException {
parser.require(XmlPullParser.START_TAG, ns, "link");
String link = readText(parser);
parser.require(XmlPullParser.END_TAG, ns, "link");
return link;
}
private String readTitle(XmlPullParser parser) throws XmlPullParserException, IOException {
parser.require(XmlPullParser.START_TAG, ns, "title");
String title = readText(parser);
parser.require(XmlPullParser.END_TAG, ns, "title");
return title;
}
private String readDate(XmlPullParser parser) throws XmlPullParserException, IOException {
parser.require(XmlPullParser.START_TAG, ns, "pubDate");
String pubDate = readText(parser);
parser.require(XmlPullParser.END_TAG, ns, "pubDate");
return pubDate;
}
// For the tags title and link, extract their text values.
private String readText(XmlPullParser parser) throws IOException, XmlPullParserException {
String result = "";
if (parser.next() == XmlPullParser.TEXT) {
result = parser.getText();
parser.nextTag();
}
return result;
}
}
Constants.java:
package com.hfad.teen10magazine;
public class Constants {
public static final String TAG = "Teen10MagazineApp";
}
RssAdapter.java:
package com.hfad.teen10magazine;
import java.util.List;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class RssAdapter extends BaseAdapter {
/* puts the RSS items in a list */
private final List<RssItem> items;
private final Context context;
public RssAdapter(Context context, List<RssItem> items) {
this.items = items;
this.context = context;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int id) {
return id;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = View.inflate(context, R.layout.rss_item, null);
holder = new ViewHolder();
holder.itemTitle = (TextView) convertView.findViewById(R.id.itemTitle);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.itemTitle.setText(items.get(position).getTitle());
return convertView;
}
static class ViewHolder {
TextView itemTitle;
}
}
Along with the main codes, for the sake of time, I will post the codes of one category that works (the fragment it is placed in and the RssService used to get it) and the codes of one that doesn't work. If you need more information or codes, please contact me and I will be happy to provide information:
LifeStyleFragment.java (Works):
package com.hfad.teen10magazine;
import android.app.Fragment;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.ResultReceiver;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
import java.util.List;
public class LifestyleFragment extends Fragment implements AdapterView.OnItemClickListener {
private ProgressBar progressBar;
private ListView listView;
private View view;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (view == null) {
view = inflater.inflate(R.layout.fragment_layout, container, false);
progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
listView = (ListView) view.findViewById(R.id.listView);
listView.setOnItemClickListener(this);
startService();
} else {
// If we are returning from a configuration change:
// "view" is still attached to the previous view hierarchy
// so we need to remove it and re-attach it to the current one
ViewGroup parent = (ViewGroup) view.getParent();
parent.removeView(view);
}
return view;
}
private void startService() {
Intent intent = new Intent(getActivity(), RssService_Lifestyle.class);
intent.putExtra(RssService_Lifestyle.RECEIVER, resultReceiver);
getActivity().startService(intent);
}
private final ResultReceiver resultReceiver = new ResultReceiver(new Handler()) {
#SuppressWarnings("unchecked")
#Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
List<RssItem> items = (List<RssItem>) resultData.getSerializable(RssService_Lifestyle.ITEMS);
if (items != null) {
RssAdapter adapter = new RssAdapter(getActivity(), items);
listView.setAdapter(adapter);
} else {
Toast.makeText(getActivity(), "An error occurred while downloading the rss feed.",
Toast.LENGTH_LONG).show();
}
progressBar.setVisibility(View.GONE);
listView.setVisibility(View.VISIBLE);
};
};
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
RssAdapter adapter = (RssAdapter) parent.getAdapter();
RssItem item = (RssItem) adapter.getItem(position);
Uri uri = Uri.parse(item.getLink());
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
}
RssService_Lifestyle.java:
package com.hfad.teen10magazine;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.net.URL;
import java.util.List;
import org.xmlpull.v1.XmlPullParserException;
import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.os.ResultReceiver;
import android.util.Log;
public class RssService_Lifestyle extends IntentService {
/* parse the rss feed on lifestyle and send the list of items to LifestyleFragment */
private static final String RSS_LINK = "http://www.teen10mag.com/category/lifestyle/feed/";
public static final String ITEMS = "items";
public static final String RECEIVER = "receiver";
public RssService_Lifestyle() {
super("RssService_Lifestyle");
}
#Override
protected void onHandleIntent(Intent intent) {
Log.d(Constants.TAG, "Service started");
List<RssItem> rssItems = null;
try {
RssParser parser = new RssParser();
rssItems = parser.parse(getInputStream(RSS_LINK));
} catch (XmlPullParserException | IOException e) {
Log.w(e.getMessage(), e);
}
Bundle bundle = new Bundle();
bundle.putSerializable(ITEMS, (Serializable) rssItems);
ResultReceiver receiver = intent.getParcelableExtra(RECEIVER);
receiver.send(0, bundle);
}
public InputStream getInputStream(String link) {
try {
URL url = new URL(link);
return url.openConnection().getInputStream();
} catch (IOException e) {
Log.w(Constants.TAG, "Exception while retrieving the input stream", e);
return null;
}
}
}
AcademicsFragment.java (Doesn't work):
package com.hfad.teen10magazine;
import java.util.List;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.ResultReceiver;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
public class AcademicsFragment extends Fragment implements AdapterView.OnItemClickListener {
private ProgressBar progressBar;
private ListView listView;
private View view;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (view == null) {
view = inflater.inflate(R.layout.fragment_layout, container, false);
progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
listView = (ListView) view.findViewById(R.id.listView);
listView.setOnItemClickListener(this);
startService();
} else {
// If we are returning from a configuration change:
// "view" is still attached to the previous view hierarchy
// so we need to remove it and re-attach it to the current one
ViewGroup parent = (ViewGroup) view.getParent();
parent.removeView(view);
}
return view;
}
private void startService() {
Intent intent = new Intent(getActivity(), RssService_Academics.class);
intent.putExtra(RssService_Academics.RECEIVER, resultReceiver);
getActivity().startService(intent);
}
private final ResultReceiver resultReceiver = new ResultReceiver(new Handler()) {
#SuppressWarnings("unchecked")
#Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
List<RssItem> items = (List<RssItem>) resultData.getSerializable(RssService_Academics.ITEMS);
if (items != null) {
RssAdapter adapter = new RssAdapter(getActivity(), items);
listView.setAdapter(adapter);
} else {
Toast.makeText(getActivity(), "An error occurred while downloading the rss feed.",
Toast.LENGTH_LONG).show();
}
progressBar.setVisibility(View.GONE);
listView.setVisibility(View.VISIBLE);
}
};
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
RssAdapter adapter = (RssAdapter) parent.getAdapter();
RssItem item = (RssItem) adapter.getItem(position);
Uri uri = Uri.parse(item.getLink());
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
}
RssService_Academics.java:
package com.hfad.teen10magazine;
import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.os.ResultReceiver;
import android.util.Log;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.net.URL;
import java.util.List;
public class RssService_Academics extends IntentService {
/* parse the rss feed on academics and send the list of items to AcademicsFragment */
private static final String RSS_LINK = "http://www.teen10mag.com/category/academics/feed/";
public static final String ITEMS = "items";
public static final String RECEIVER = "receiver";
public RssService_Academics() {
super("RssService_Academics");
}
#Override
protected void onHandleIntent(Intent intent) {
Log.d(Constants.TAG, "Service started");
List<RssItem> rssItems = null;
try {
RssParser parser = new RssParser();
rssItems = parser.parse(getInputStream(RSS_LINK));
} catch (XmlPullParserException | IOException e) {
Log.w(e.getMessage(), e);
}
Bundle bundle = new Bundle();
bundle.putSerializable(ITEMS, (Serializable) rssItems);
ResultReceiver receiver = intent.getParcelableExtra(RECEIVER);
receiver.send(0, bundle);
}
public InputStream getInputStream(String link) {
try {
URL url = new URL(link);
return url.openConnection().getInputStream();
} catch (IOException e) {
Log.w(Constants.TAG, "Exception while retrieving the input stream", e);
return null;
}
}
}
This is my first question, so I tried to be as detailed as possible. If my explanations were unreasonably lengthy, I do apologize. This is also my first time coding something this extensive, so forgive me if I seem to make amateur mistakes...
Thank you in advance for all of your help!!
[EDIT]
When I click on the category that doesn't work, the logcat turns up like this:
09-21 19:29:59.237 1541-1866/system_process W/ActivityManager: Unable to start service Intent { cmp=com.hfad.teen10magazine/.RssService_News (has extras) } U=0: not found
09-21 19:30:13.209 2808-2808/com.hfad.teen10magazine I/Choreographer: Skipped 31 frames! The application may be doing too much work on its main thread.
09-21 19:30:21.122 2808-2814/com.hfad.teen10magazine W/art: Suspending all threads took: 13.025ms`
We have code that creates a list view with detailed view upon click. There is a wrapper class called drink content containing a drink object and a static code segment that makes a call to an asyncTask that calls our web service. We need to build the URL based on data from another activity but I don't understand the way in which the object is created. We can't seem to replace the general DrinkContent references in the list and detail fragments with a single reference to an instantiated instance of DrinkContent. We wanted to use the instantiated instance of drink content so we could write a constructor that would take in URL parameters generated during another activity. We can pass the URL data to the fragments, but when a constructor was written multiple instances of Drink content were being created and our web service request didn't work. We are storing the parameters in another activities shared preferences and passing them to the new activity.
Code for DrinkListActivity:
package com.cs4720.drinkengine_android;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.NavUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class DrinkListActivity extends FragmentActivity
implements DrinkListFragment.Callbacks {
private boolean mTwoPane;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drink_list);
if (findViewById(R.id.drink_detail_container) != null) {
mTwoPane = true;
((DrinkListFragment) getSupportFragmentManager()
.findFragmentById(R.id.drink_list))
.setActivateOnItemClick(true);
}
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(DrinkListActivity.this, LeaderboardActivity.class);
startActivity(i);
}
});
}
public void onItemSelected(String id) {
if (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putString(DrinkDetailFragment.ARG_ITEM_ID, id);
DrinkDetailFragment fragment = new DrinkDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.drink_detail_container, fragment)
.commit();
} else {
Intent detailIntent = new Intent(this, DrinkDetailActivity.class);
detailIntent.putExtra(DrinkDetailFragment.ARG_ITEM_ID, id);
startActivity(detailIntent);
}
}
}
code for DrinkListFragment
package com.cs4720.drinkengine_android;
import com.cs4720.drinkengine_android.dummy.DrinkContent;
import com.cs4720.drinkengine_android.dummy.DrinkContent.GetDrinksTask;
import android.R;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class DrinkListFragment extends ListFragment {
private static final String STATE_ACTIVATED_POSITION = "activated_position";
private Callbacks mCallbacks = sDummyCallbacks;
private int mActivatedPosition = ListView.INVALID_POSITION;
public interface Callbacks {
public void onItemSelected(String id);
}
private static Callbacks sDummyCallbacks = new Callbacks() {
public void onItemSelected(String id) {
}
};
public DrinkListFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<DrinkContent.Drink>(getActivity(),
R.layout.simple_list_item_activated_1,
R.id.text1,
DrinkContent.ITEMS));
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (savedInstanceState != null && savedInstanceState
.containsKey(STATE_ACTIVATED_POSITION)) {
setActivatedPosition(savedInstanceState.getInt(STATE_ACTIVATED_POSITION));
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (!(activity instanceof Callbacks)) {
throw new IllegalStateException("Activity must implement fragment's callbacks.");
}
mCallbacks = (Callbacks) activity;
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = sDummyCallbacks;
}
#Override
public void onListItemClick(ListView listView, View view, int position, long id) {
super.onListItemClick(listView, view, position, id);
mCallbacks.onItemSelected(DrinkContent.ITEMS.get(position).name);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mActivatedPosition != ListView.INVALID_POSITION) {
outState.putInt(STATE_ACTIVATED_POSITION, mActivatedPosition);
}
}
public void setActivateOnItemClick(boolean activateOnItemClick) {
getListView().setChoiceMode(activateOnItemClick
? ListView.CHOICE_MODE_SINGLE
: ListView.CHOICE_MODE_NONE);
}
public void setActivatedPosition(int position) {
if (position == ListView.INVALID_POSITION) {
getListView().setItemChecked(mActivatedPosition, false);
} else {
getListView().setItemChecked(position, true);
}
mActivatedPosition = position;
}
}
code for DrinkDetailActivity
package com.cs4720.drinkengine_android;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.NavUtils;
import android.view.MenuItem;
public class DrinkDetailActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drink_detail);
getActionBar().setDisplayHomeAsUpEnabled(true);
if (savedInstanceState == null) {
Bundle arguments = new Bundle();
arguments.putString(DrinkDetailFragment.ARG_ITEM_ID,
getIntent().getStringExtra(DrinkDetailFragment.ARG_ITEM_ID));
DrinkDetailFragment fragment = new DrinkDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.add(R.id.drink_detail_container, fragment)
.commit();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
NavUtils.navigateUpTo(this, new Intent(this, DrinkListActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
code for drinkDetailFragment
package com.cs4720.drinkengine_android;
import com.cs4720.drinkengine_android.dummy.DrinkContent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class DrinkDetailFragment extends Fragment {
public static final String ARG_ITEM_ID = "item_id";
DrinkContent.Drink mItem;
public DrinkDetailFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments().containsKey(ARG_ITEM_ID)) {
mItem = DrinkContent.ITEM_MAP.get(getArguments().getString(ARG_ITEM_ID));
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_drink_detail, container, false);
if (mItem != null) {
String miss="";
if(mItem.missing == 0){
miss = "You can make this Drink!";
}
else{
miss = "Missing "+ mItem.missing + " ingredients";
}
StringBuilder sb = new StringBuilder();
sb.append("Name: " + mItem.name
+ "\n" + miss
+ "\nDecription: " + mItem.description
+ "\nCalories: " + mItem.calories
+ "\nStrength: " + mItem.strength
+ "\nIngredients: \n");
for(int i = 0; i < mItem.units.size(); i++)
sb.append(mItem.units.get(i) + " " + mItem.ingredients.get(i) + "\n");
((TextView) rootView.findViewById(R.id.drink_detail)).setText(sb.toString());
}
return rootView;
}
}
code for DrinkContent
package com.cs4720.drinkengine_android.dummy;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.util.Log;
public class DrinkContent {
public static class Drink {
public String name;
public int missing;
public String description;
public int calories;
public int strength;
public List<String> units;
public List<String> ingredients;
public Drink(String name) {
super();
this.name = name;
}
#Override
public String toString() {
return name;
}
}
public static String url = "http://drinkengine.appspot.com/view";
public static List<Drink> ITEMS = new ArrayList<Drink>();
public static Map<String, Drink> ITEM_MAP = new HashMap<String, Drink>();
static{
new GetDrinksTask().execute(url);
}
private static void addItem(Drink item) {
ITEMS.add(item);
ITEM_MAP.put(item.name, item);
}
public static String getJSONfromURL(String url) {
// initialize
InputStream is = null;
String result = "";
// http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("DrinkEngine", "Error in http connection " + e.toString());
}
// convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("DrinkEngine", "Error converting result " + e.toString());
}
return result;
}
// The definition of our task class
public static class GetDrinksTask extends AsyncTask<String, Integer, String> {
SharedPreferences prefs;
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... params) {
String url = params[0];
ArrayList<Drink> lcs = new ArrayList<Drink>();
try {
String webJSON = getJSONfromURL(url);
JSONArray drinks = new JSONArray(webJSON);
for (int i = 0; i < drinks.length(); i++) {
JSONObject jo = drinks.getJSONObject(i);
Drink current = new Drink(jo.getString("name"));
current.missing = Integer.parseInt(jo.getString("missing"));
current.description = jo.getString("description");
current.calories = Integer.parseInt(jo.getString("calories"));
current.strength = Integer.parseInt(jo.getString("strength"));
JSONArray units = jo.getJSONArray("units");
current.units = new ArrayList<String>();
for(int j = 0; j < units.length(); j++){
current.units.add(units.getString(j));
}
JSONArray ingredients = jo.getJSONArray("ingredients");
current.ingredients = new ArrayList<String>();
for(int j = 0; j < ingredients.length(); j++){
current.ingredients.add(ingredients.getString(j));
}
addItem(current);
}
} catch (Exception e) {
Log.e("DrinkEngine", "JSONPARSE:" + e.toString());
}
return "Done!";
}
#Override
protected void onProgressUpdate(Integer... ints) {
}
#Override
protected void onPostExecute(String result) {
// tells the adapter that the underlying data has changed and it
// needs to update the view
}
}
}
So now that youve seen the code the question might make more sense. We need to access our URL params from within drink content. But those parameters changed based on user input from another activity. We store those params in the other activities shared prefs and them pass them the DrinkListActivity and attempted to write a constructor that would take in the params and build the url properly. This did not work when we replaced the generalized DrinkContent and DrinkContent.LIST references with our instance we created. So basically how do we get the info inside of this class from our shared prefs?
SharedPreferences are shared across application level and not only activity level. It can actually be shared between applications if it is set to public. You should go read the documentation here and here as it explains this quite well.