How to identify that I method was called by a fragment? - android

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));
}

Related

Not annotated parameter overrides #NonNull parameter

#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.

android - URL encode from user input

I will encode user input into a single URL, I use Uri.encode but error response remains 400. how to make the encode work?
the result is that "space" is replaced with "%20" but the response still fails
And this is my code.,
public void OnQuerySubmit() {
searchView.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
String UrlEncode = AppConfig.URL_GETJOBS + Uri.encode(query);
progressDialog.setMessage("Mencari...");
showDialog();
jobList.clear();
getJobs(UrlEncode);
homeRecyclerViewAdapter.notifyDataSetChanged();
hideDialog();
return false;
}
});
}
public List<Job> getJobs(String urlGetjobs) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, urlGetjobs, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, "onResponse: " + response.toString());
try {
boolean error = response.getBoolean("error");
if(!error) {
JSONArray transaksiArray = response.getJSONArray("transaksi");
for(int i = 0; i < transaksiArray.length(); i++) {
JSONObject seluruhTrans = transaksiArray.getJSONObject(i);
Job job = new Job();
job.setTitle(seluruhTrans.getString("title"));
job.setNamaPerusahaan(seluruhTrans.getString("nama_perusahaan"));
job.setLokasi(seluruhTrans.getString("lokasi"));
job.setKriteria_1(seluruhTrans.getString("kriteria_1"));
job.setKriteria_2(seluruhTrans.getString("kriteria_2"));
job.setKriteria_3(seluruhTrans.getString("kriteria_3"));
job.setGaji(seluruhTrans.getString("gaji"));
job.setImg_logo(seluruhTrans.getString("img_logo"));
job.setTanggal(seluruhTrans.getString("tanggal"));
job.setId_post(seluruhTrans.getString("id_post"));
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("title", job.getTitle());
editor.putString("nama_perusahaan", job.getNamaPerusahaan());
editor.putString("lokasi", job.getLokasi());
editor.putString("kriteria_1", job.getKriteria_1());
editor.putString("kriteria_2", job.getKriteria_2());
editor.putString("kriteria_3", job.getKriteria_3());
editor.putString("gaji", job.getGaji());
editor.putString("img_logo", job.getImg_logo());
editor.putString("tanggal", job.getTanggal());
editor.putString("id_post", job.getId_post());
editor.commit();
jobList.add(job);
}
}
homeRecyclerViewAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof NoConnectionError || error instanceof TimeoutError || error instanceof NoConnectionError){
Toast.makeText(getActivity(), "Please Check your Connection!", Toast.LENGTH_SHORT).show();
}
}
});
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
return jobList;
}
Any help would be appreciated.
Modify your code like this
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
queue = Volley.newRequestQueue(getActivity());
searchView = view.findViewById(R.id.search_view);
recyclerView = view.findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
jobList = new ArrayList<>();
homeRecyclerViewAdapter = new HomeRecyclerViewAdapter(getActivity(), jobList);
recyclerView.setAdapter(homeRecyclerViewAdapter);
getJobs(""); //get your data as it is
OnQuerySubmit();
return view;
}
public void OnQuerySubmit() {
searchView.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
getJobs(query);
return false;
}
});
}
public void getJobs(final String query) {
StringRequest jsonObjectRequest = new StringRequest(Request.Method.GET, AppConfig.URL_GETJOBS, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "onResponse: " + response);
try {
JSONObject jsonObject=new JSONObject(response);
boolean error = jsonObject.getBoolean("error");
if (!error) {
jobList.clear();
JSONArray transaksiArray = jsonObject.JSONArray("transaksi");
....
....
....
jobList.add(job);
adapter.notifyDataSetChanged();
}
} catch (JSONException e) {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(Tag, error.toString());
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<>();
if(!TextUtils.isEmpty(query){
map.put("title", query);
}else{}
return map;
}
};
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
}
package com.mimdudin.carekkerje.Activities;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
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.Toast;
import com.android.volley.NoConnectionError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.miguelcatalan.materialsearchview.MaterialSearchView;
import com.mimdudin.carekkerje.Adapter.HomeRecyclerViewAdapter;
import com.mimdudin.carekkerje.Helper.AppController;
import com.mimdudin.carekkerje.Model.Job;
import com.mimdudin.carekkerje.R;
import com.mimdudin.carekkerje.Util.AppConfig;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import static com.android.volley.VolleyLog.TAG;
/**
* A simple {#link Fragment} subclass.
*/
public class HomeFragment extends Fragment {
private RecyclerView recyclerView;
private HomeRecyclerViewAdapter homeRecyclerViewAdapter;
private List<Job> jobList;
private RequestQueue queue;
private MaterialSearchView searchView;
private ProgressDialog progressDialog;
private SharedPreferences sharedPreferences;
public HomeFragment() {
// Required empty public constructor
}
public static HomeFragment newInstance() {
HomeFragment homeFragment = new HomeFragment();
return homeFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
queue = Volley.newRequestQueue(getActivity());
searchView = view.findViewById(R.id.search_view);
recyclerView = view.findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
jobList = new ArrayList<>();
jobList = getJobs(AppConfig.URL_GETJOBS);
homeRecyclerViewAdapter = new HomeRecyclerViewAdapter(getActivity(), jobList);
recyclerView.setAdapter(homeRecyclerViewAdapter);
homeRecyclerViewAdapter.notifyDataSetChanged();
sharedPreferences = getActivity().getSharedPreferences("data", Context.MODE_PRIVATE);
progressDialog = new ProgressDialog(getContext());
progressDialog.setCancelable(false);
OnQuerySubmit();
return view;
}
public void OnQuerySubmit(){
searchView.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
String UrlEncode = AppConfig.URL_GETJOBS + Uri.encode(query);
progressDialog.setMessage("Mencari...");
showDialog();
jobList.clear();
getJobs(UrlEncode);
homeRecyclerViewAdapter.notifyDataSetChanged();
hideDialog();
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
}
public List<Job> getJobs(String urlGetjobs) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, urlGetjobs, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, "onResponse: " + response.toString());
try {
boolean error = response.getBoolean("error");
if(!error) {
JSONArray transaksiArray = response.getJSONArray("transaksi");
for(int i = 0; i < transaksiArray.length(); i++) {
JSONObject seluruhTrans = transaksiArray.getJSONObject(i);
Job job = new Job();
job.setTitle(seluruhTrans.getString("title"));
job.setNamaPerusahaan(seluruhTrans.getString("nama_perusahaan"));
job.setLokasi(seluruhTrans.getString("lokasi"));
job.setKriteria_1(seluruhTrans.getString("kriteria_1"));
job.setKriteria_2(seluruhTrans.getString("kriteria_2"));
job.setKriteria_3(seluruhTrans.getString("kriteria_3"));
job.setGaji(seluruhTrans.getString("gaji"));
job.setImg_logo(seluruhTrans.getString("img_logo"));
job.setTanggal(seluruhTrans.getString("tanggal"));
job.setId_post(seluruhTrans.getString("id_post"));
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("title", job.getTitle());
editor.putString("nama_perusahaan", job.getNamaPerusahaan());
editor.putString("lokasi", job.getLokasi());
editor.putString("kriteria_1", job.getKriteria_1());
editor.putString("kriteria_2", job.getKriteria_2());
editor.putString("kriteria_3", job.getKriteria_3());
editor.putString("gaji", job.getGaji());
editor.putString("img_logo", job.getImg_logo());
editor.putString("tanggal", job.getTanggal());
editor.putString("id_post", job.getId_post());
editor.commit();
jobList.add(job);
}
}
homeRecyclerViewAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof NoConnectionError || error instanceof TimeoutError || error instanceof NoConnectionError){
Toast.makeText(getActivity(), "Please Check your Connection!", Toast.LENGTH_SHORT).show();
}
}
});
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
return jobList;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_main, menu);
MenuItem item = menu.findItem(R.id.action_search);
searchView.setMenuItem(item);
super.onCreateOptionsMenu(menu, inflater);
}
public void showDialog() {
if (!progressDialog.isShowing()) {
progressDialog.show();
}
}
public void hideDialog(){
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
HomeRecyclerviewAdapter.java
package com.mimdudin.carekkerje.Adapter;
import android.app.FragmentManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.mimdudin.carekkerje.Activities.HomeFragment;
import com.mimdudin.carekkerje.Activities.HomeFragmentDetail;
import com.mimdudin.carekkerje.Model.Job;
import com.mimdudin.carekkerje.R;
import java.util.List;
/**
* Created by master on 12/12/17.
*/
public class HomeRecyclerViewAdapter extends RecyclerView.Adapter<HomeRecyclerViewAdapter.ViewHolder> {
private Context context;
private List<Job> jobList;
public HomeRecyclerViewAdapter(Context context, List<Job> jobs){
this.context = context;
jobList = jobs;
}
#Override
public HomeRecyclerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.home_row, parent, false);
return new ViewHolder(view, context);
}
#Override
public void onBindViewHolder(HomeRecyclerViewAdapter.ViewHolder holder, int position) {
Job job = jobList.get(position);
holder.title.setText(job.getTitle());
holder.namaPerusahaan.setText(job.getNamaPerusahaan());
holder.kriteria_1.setText(job.getKriteria_1());
holder.kriteria_2.setText(job.getKriteria_2());
holder.kriteria_3.setText(job.getKriteria_3());
holder.gaji.setText(job.getGaji());
holder.lokasi.setText(job.getLokasi());
holder.tanggal.setText(job.getTanggal());
String img_logoLink = job.getImg_logo();
Glide.with(context)
.load(img_logoLink) // URL
.apply(new RequestOptions().placeholder(android.R.drawable.ic_dialog_info)
.error(android.R.drawable.ic_dialog_alert).centerCrop().dontAnimate()
// .centerCrop(), .crossFade(), .thumbnail(), .dontAnimate(), .dontTransform() BitmapTransformation(.circleCrop())
)
.into(holder.img_logo); //TARGET GAMBAR YANG NAK DIUBAH
}
#Override
public int getItemCount() {
return jobList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView title;
TextView namaPerusahaan;
TextView lokasi;
TextView kriteria_1;
TextView kriteria_2;
TextView kriteria_3;
TextView gaji;
ImageView img_logo;
TextView tanggal;
public ViewHolder(final View itemView, final Context ctx) {
super(itemView);
context = ctx;
title = itemView.findViewById(R.id.titleID);
namaPerusahaan = itemView.findViewById(R.id.namaPerusahaanID);
kriteria_1 = itemView.findViewById(R.id.satuTv);
kriteria_2 = itemView.findViewById(R.id.duaTv);
kriteria_3 = itemView.findViewById(R.id.tigaTv);
gaji = itemView.findViewById(R.id.gajiID);
lokasi = itemView.findViewById(R.id.lokasiID);
img_logo = itemView.findViewById(R.id.img_logoID);
tanggal = itemView.findViewById(R.id.tanggalID);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
HomeFragmentDetail fragmentDetail = new HomeFragmentDetail();
Bundle bundle = new Bundle();
Job job = jobList.get(getAdapterPosition());
bundle.putSerializable("job", job);
fragmentDetail.setArguments(bundle);
AppCompatActivity activity = (AppCompatActivity) itemView.getContext();
android.support.v4.app.FragmentManager fragmentManager = activity.getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction().addToBackStack(null);
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
fragmentTransaction.replace(R.id.frame_fragmenthome, fragmentDetail);
fragmentTransaction.commit();
//// Intent intent = new Intent(context, HomeDetailActivity.class);
//// intent.putExtra("job", job);
//// ctx.startActivity(intent);
}
});
}
}
}
HomeFragmentDetail.java
package com.mimdudin.carekkerje.Activities;
import android.content.Context;
import android.net.Uri;
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;
import com.mimdudin.carekkerje.Model.Job;
import com.mimdudin.carekkerje.R;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* to handle interaction events.
*/
public class HomeFragmentDetail extends Fragment {
private TextView tvDeskripsi;
private TextView tvIndustri;
public HomeFragmentDetail() {
// Required empty public constructor
}
public static HomeFragmentDetail newInstance(){
HomeFragmentDetail homeFragmentDetail = new HomeFragmentDetail();
return homeFragmentDetail;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home_fragment_detail, container, false);
tvDeskripsi = view.findViewById(R.id.tvDeskripsi);
tvIndustri = view.findViewById(R.id.tvIndustri);
Bundle bundle = getArguments();
Job job = (Job) bundle.getSerializable("job");
String PostID = job.getId_post();
String titleID = job.getTitle();
tvDeskripsi.setText(PostID);
tvIndustri.setText(titleID);
return view;
// DataHolder dataholder=new DataHolder("1","TestName");
// Bundle bundle=new Bundle();
// bundle.putSerializable("obj",dataholder);
// Fragment fragment=new FragmentB();
// fragment.setArguments(bundle);
// fragmentManager = getActivity(). getSupportFragmentManager();
// fragmentTransaction = fragmentManager .beginTransaction();
// fragmentTransaction.add(R.id.container, fragment);
// fragmentTransaction.commit();
//Job job = (Job) getIntent.getSerializableExtra("job");
// Bundle bundle = getArguments();
// Job job = (Job) bundle.getSerializable("job");
// String jobID = job.getId_post();
// String titleID = job.getTitle();
}
}
AppConfig.java
package com.mimdudin.carekkerje.Util;
/**
* Created by master on 10/12/17.
*/
public class AppConfig {
public static final String URL = "http://192.168.43.142/Carekkerje/v1";
public static final String URL_REGISTER = URL + "/daftarUser";
public static final String URL_LOGIN = URL + "/loginUser";
public static final String URL_GETJOBS = URL + "/seluruhLowongan/";
public static final String URL_GETJOBSS = URL + "/seluruhLowongan/:title";
}

MainActvity not getting updated when App is first launched

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();

Grid-view is not formed in horizontal-scrolling-pages like home screen when app is in Background or Process is died

I am developing Horizontal Scrolling pages and tabs
MY app is working well in all devices in foreground, but when it goes to background, after one hour, the logs saying that Process com.example.myapp has died. When i reopen the app , the gridview data is not appearing but when scrolling horizontally , getView() method displaying all data like images and text.
that means app has data but view is not formed when process has died. And if i press back button and re-open the app, It is working good
My MainActivity.java is here
package com.bbgusa.bbgdemo.ui.phone;
import java.util.List;
import java.util.Vector;
import org.json.JSONObject;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.TabHost;
import com.bbgusa.bbgdemo.R;
import com.bbgusa.bbgdemo.listener.phone.CustomViewPager;
import com.bbgusa.bbgdemo.ui.chat.phone.ChatFragmentTab;
import com.bbgusa.bbgdemo.ui.dialpad.phone.DialerFragment;
import com.bbgusa.bbgdemo.ui.home.phone.AlarmFragmentPhone;
import com.bbgusa.bbgdemo.ui.home.phone.HomeFragment;
import com.bbgusa.bbgdemo.ui.home.phone.HomeFragmentTab;
import com.bbgusa.bbgdemo.ui.home.phone.InfoFragPhone;
import com.bbgusa.bbgdemo.ui.home.phone.MapPhone;
import com.bbgusa.bbgdemo.ui.home.phone.WeatherFragmentPhone;
import com.bbgusa.bbgdemo.ui.messages.phone.MessagesFragment;
import com.bbgusa.bbgdemo.ui.settings.phone.AboutFragment;
import com.bbgusa.bbgdemo.ui.tablet.ConstantsManager;
import com.bbgusa.bbgdemo.ui.tablet.OnFragmentChangedListenerPhone;
import com.bbgusa.bbgdemo.utils.common.UConnectUtils;
public class MainActivity extends FragmentActivity implements TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener, OnFragmentChangedListenerPhone {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_phone);
this.initialiseTabHost(savedInstanceState);
initialiseViewPager();
}
/**
* Initialise ViewPager
*/
private void initialiseViewPager() {
List<Fragment> fragments = new Vector<Fragment>();
fragments.add(Fragment.instantiate(this,HomeFragmentTab.class.getName()));
fragments.add(Fragment.instantiate(this, DialerFragment.class.getName()));
fragments.add(Fragment.instantiate(this,MessagesFragment.class.getName()));
fragments.add(Fragment.instantiate(this,ChatFragmentTab.class.getName()));
fragments.add(Fragment.instantiate(this, AboutFragment.class.getName()));
this.mPagerAdapter = new PagerAdapter(super.getSupportFragmentManager(), fragments);
this.mViewPager = (CustomViewPager) findViewById(R.id.tabviewpager);
this.mViewPager.setAdapter(this.mPagerAdapter);
this.mViewPager.setOnPageChangeListener(this);
this.mViewPager.setOffscreenPageLimit(5);
this.mViewPager.setCurrentItem(0);
}
#Override
public void onFragmentChangePhone(JSONObject response, String whichView, String title, String mPhoneNo) {
Bundle b = new Bundle();
if(response != null)
b.putString("JSONObject", response.toString());
if(title != null)
b.putString("Title", title);
String propertyId = UConnectUtils.getPropertyId(mPref, getString(R.string.property_id));
b.putString(UConnectUtils.PROPERTY_ID_KEY, propertyId);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
Fragment fragment = null;
if (whichView.equals(ConstantsManager.GRIDVIEWPAGER)) {
// getSupportFragmentManager().popBackStack();
fragment = new HomeFragment();
} else if (whichView.equals(ConstantsManager.WEATHER)) {
fragment = new WeatherFragmentPhone();
}else if (whichView.equals(ConstantsManager.ALARM)) {
fragment = new AlarmFragmentPhone();
}else if (whichView.equals(ConstantsManager.MAPS)) {
fragment = new MapPhone();
}else if (whichView.equals(ConstantsManager.HELP)) {
fragment = new InfoFragPhone();
}
if (whichView.equals(ConstantsManager.MAPS)) { // to show plus-icon on map top right corner
HomeFragment.getInstance().onGridViewVisibilityChanged(true);
HomeFragmentTab.getInstance().onFragmentTabChange(View.VISIBLE , title, "", View.VISIBLE);
} else if (!whichView.equals(ConstantsManager.GRIDVIEWPAGER)) {
HomeFragment.getInstance().onGridViewVisibilityChanged(true);
HomeFragmentTab.getInstance().onFragmentTabChange(View.VISIBLE , title, mPhoneNo, View.GONE);
}
fragment.setArguments(b);
ft.add(R.id.main_home_frag, fragment);
if (whichView.equals(ConstantsManager.GRIDVIEWPAGER)) {
fragmentManager.popBackStack();
} else {
ft.addToBackStack(fragment.toString());
}
ft.commit();
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
}
#Override
public void onTabChanged(String tabId) {
// TODO Auto-generated method stub
}
}
and my HomeFragmentTab.java is
package com.bbgusa.bbgdemo.ui.home.phone;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.bbgusa.bbgdemo.R;
import com.bbgusa.bbgdemo.ui.phone.MainActivity;
import com.bbgusa.bbgdemo.ui.tablet.ConstantsManager;
import com.bbgusa.bbgdemo.ui.tablet.OnFragmentTabChangedListener;
#SuppressLint("NewApi")
public class HomeFragmentTab extends Fragment implements OnFragmentTabChangedListener{
private static final String TAG = HomeFragmentTab.class.getSimpleName();
private static HomeFragmentTab tab;
private MainActivity activityPhone;
public static HomeFragmentTab getInstance() {
return tab;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
activityPhone = (MainActivity) activity;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v;
if (container == null) {
return null;
}
Log.i(TAG, "onCreateView");
v = inflater.inflate(R.layout.hometab_phone, container, false);
tab = this;
activityPhone.onFragmentChangePhone(null, ConstantsManager.GRIDVIEWPAGER, getResources().getString(R.string.app_name), "");
return v;
}
#Override
public void onFragmentTabChange(int i, String title, String mPhoneNo, int mapV) {
}
}
and HomeFragment.java is
package com.bbgusa.bbgdemo.ui.home.phone;
import java.util.Locale;
import org.json.JSONArray;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.bbgusa.bbgdemo.R;
import com.bbgusa.bbgdemo.ui.ImageCacheManager;
import com.bbgusa.bbgdemo.ui.cms.tablet.TestTopics;
import com.bbgusa.bbgdemo.ui.cms.tablet.TopicList;
import com.bbgusa.bbgdemo.ui.phone.MainActivity;
import com.bbgusa.bbgdemo.ui.tablet.onGridViewVisibilityChangedListener;
import com.bbgusa.bbgdemo.utils.common.UCConstants;
import com.bbgusa.bbgdemo.utils.common.UConnectUtils;
import com.viewpagerindicator.IconPageIndicator;
import com.viewpagerindicator.IconPagerAdapter;
import com.viewpagerindicator.PageIndicator;
public class HomeFragment extends Fragment implements onGridViewVisibilityChangedListener{
private static final String TAG = HomeFragment.class.getSimpleName();
private ViewPager mViewPager;
private MainActivity activity;
private PageIndicator mIndicator;
private Animation mRotateAnim;
private Dialog indiacatorDialog;
private LinearLayout homeFragmentLL;
private static HomeFragment homeFragment;
public static final HomeFragment getInstance() {
return homeFragment;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.activity = (MainActivity) activity;
}
#Override
public void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "onCreate");
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (container == null) {
return null;
}
View v = inflater.inflate(R.layout.home_phone, container, false);
homeFragment = this;
UConnectUtils.setLauncher(true);
mViewPager = (ViewPager) v.findViewById(R.id.viewpager);
mIndicator = (IconPageIndicator) v.findViewById(R.id.indicator);
homeFragmentLL = (LinearLayout) v.findViewById(R.id.homeFragment);
indiacatorDialog = new Dialog(getActivity());
indiacatorDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
indiacatorDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
indiacatorDialog.setContentView(R.layout.indicator_dialog);
indiacatorDialog.setCanceledOnTouchOutside(false);
Window window = indiacatorDialog.getWindow();
window.setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
mRotateAnim = AnimationUtils.loadAnimation(getActivity(), R.anim.rotate_and_scale);
UConnectUtils.addAnimationFrameCount(mRotateAnim);
indicatorAnim();
// for property id
// if (activity.isInterNetAvailable()) {
Log.i(TAG, "onCreateView========== isInterNetAvailable");
new CmsPropertyAsync(activity).execute(UCConstants.CMS_CONFIG_URL, UCConstants.CMS_CONFIG_KEY);
// }
return v;
}
protected void parseJson(JSONObject rootResponce) {
TestTopics.imageUrls.clear();
TestTopics.titles.clear();
TestTopics.mMainMenuID.clear();
TestTopics.mViewType.clear();
TestTopics.mPhoneNo.clear();
try {
//get the Version
String version = rootResponce.optString("VERSION");
SharedPreferences mPref;
SharedPreferences.Editor edit;
mPref = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
edit = mPref.edit();
edit.putString(getResources().getString(R.string.pref_cms_version_key), version).commit();
JSONArray jsonArray = rootResponce.getJSONArray("MAINMENU");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject childMenuObject = jsonArray.getJSONObject(i);
int mainMenuID = childMenuObject.optInt("mainMenuId");
String title = childMenuObject.optString("title");
String viewType = childMenuObject.optString("viewType");
String imageUrl = childMenuObject.optString("imageUrl");
String phoneNo = childMenuObject.optString("phoneNo");
TestTopics.mMainMenuID.add(mainMenuID);
TestTopics.imageUrls.add(imageUrl);
TestTopics.titles.add(title);
TestTopics.mViewType.add(viewType);
TestTopics.mPhoneNo.add(phoneNo);
}
// Create a TopicList for this demo. Save it as the shared instance
// in
// TopicList
String sampleText = getResources().getString(R.string.sample_topic_text);
TopicList tlist = new TopicList(sampleText);
TopicList.setInstance(tlist);
// Create an adapter object that creates the fragments that we need
// to display the images and titles of all the topics.
MyAdapter mAdapter = new MyAdapter(getActivity().getSupportFragmentManager(), tlist, getResources());
// mViewPager.removeAllViews();
mViewPager.setAdapter(mAdapter);
// mViewPager.setPageTransformer(true, new DepthPageTransformer());
mIndicator.setViewPager(mViewPager);
mIndicator.setCurrentItem(0);
mIndicator.notifyDataSetChanged();
ViewTreeObserver observer = mViewPager.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#SuppressLint("NewApi")
#SuppressWarnings("deprecation")
#Override
public void onGlobalLayout() {
mViewPager.bringChildToFront(mViewPager.getChildAt(0));
if(Build.VERSION.SDK_INT >= UCConstants.ICE_CREAM_SANDWICH_MR1){
mViewPager.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}else{
mViewPager.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
}
});
/*Fragment f = new GridViewFragment();
FragmentTransaction t = getFragmentManager().beginTransaction();
t.replace(R.id.main_home_frag, f);
t.commit();*/
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Adapter class
*
* This adapter class sets up GridFragment objects to be displayed by a
* ViewPager.
*/
public static class MyAdapter extends FragmentStatePagerAdapter implements IconPagerAdapter {
private TopicList mTopicList;
private int mNumItems = 0;
private int mNumFragments = 0;
/**
* Return a new adapter.
*/
public MyAdapter(FragmentManager fm, TopicList db, Resources res) {
super(fm);
setup(db, res);
}
/**
* Get the number of fragments to be displayed in the ViewPager.
*/
#Override
public int getCount() {
Log.i(TAG, "getCount : mNumFragments = "+mNumFragments);
return mNumFragments;
}
/**
* Return a new GridFragment that is used to display n items at the
* position given.
*
* #param position
* int - the position of the fragement; 0..numFragments-1
*/
#Override
public Fragment getItem(int position) {
// Create a new Fragment and supply the fragment number, image
// position, and image count as arguments.
// (This was how arguments were handled in the original pager
// example.)
Bundle args = new Bundle();
args.putInt("num", position + 1);
args.putInt("firstImage", position * mNumItems);
// The last page might not have the full number of items.
int imageCount = mNumItems;
if (position == (mNumFragments - 1)) {
int numTopics = mTopicList.getNumTopics();
int rem = numTopics % mNumItems;
if (rem > 0)
imageCount = rem;
}
args.putInt("imageCount", imageCount);
args.putSerializable("topicList", TopicList.getInstance());
// Return a new GridFragment object.
Log.i(TAG, "created fragmenat number:==== "+position+" "+1);
GridViewFragmentPhone f = new GridViewFragmentPhone();
f.setArguments(args);
Log.i(TAG, "getItem : imageCount = "+imageCount);
return f;
}
/**
* Set up the adapter using information from a TopicList and resources
* object. When this method completes, all the instance variables of the
* adapter are valid;
*
* #param tlist
* TopicList
* #param res
* Resources
* #return void
*/
void setup(TopicList tlist, Resources res) {
mTopicList = tlist;
if ((tlist == null) || (res == null)) {
mNumItems = 2;//DEFAULT_NUM_ITEMS;
mNumFragments = 2;//DEFAULT_NUM_FRAGMENTS;
} else {
int numTopics = tlist.getNumTopics();
int numRowsGV = res.getInteger(R.integer.num_of_rows_gridview);
int numColsGV = res.getInteger(R.integer.num_of_cols_gridview);
int numTopicsPerPage = numRowsGV * numColsGV;
int numFragments = numTopics / numTopicsPerPage;
if (numTopics % numTopicsPerPage != 0)
numFragments++; // Add one if there is a partial page
mNumFragments = numFragments;
mNumItems = numTopicsPerPage;
}
} // end setup
#Override
public int getIconResId(int index) {
int[] ICON = new int[mNumFragments];
for (int i = 0; i < mNumFragments; i++) {
ICON[i] = R.drawable.slidericon;
}
return ICON[index % ICON.length];
}
} // end class MyAdapter
#Override
public void onGridViewVisibilityChanged(boolean hide) {
if(hide){
homeFragmentLL.setVisibility(View.GONE);
}else {
homeFragmentLL.setVisibility(View.VISIBLE);
}
}
#Override
public void onDetach() {
super.onDetach();
activity = null;
}
#Override
public void onDestroy() {
super.onDestroy();
}
private class CmsPropertyAsync extends AsyncTask<String, Void, String> {
MainActivity context;
CmsPropertyAsync(MainActivity activityTab) {
context = activityTab;
}
#Override
protected String doInBackground(String... params) {
String propertyId = UConnectUtils.getPropertyId(PreferenceManager.getDefaultSharedPreferences(context),getResources().getString(R.string.property_id));
if(propertyId != null && propertyId.length() > 0){
return propertyId;
}
return UConnectUtils.requestPropertyId(params[0], params[1]);
}
#Override
protected void onPostExecute(String propertyId) {
if(propertyId == null){
indiacatorDialog.dismiss();
showPropertyIdTimeoutAlert(getActivity());
return;
}
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
editor.putString(getString(R.string.property_id),propertyId).commit();
String url = null;
String locale = Locale.getDefault().getLanguage();
url = UCConstants.CMS_BASE_URL+"mainMenu?propertyId="+propertyId+"&lang="+locale;
JsonObjectRequest jsObjRequest = new JsonObjectRequest(
Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
parseJson(response);
indiacatorDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (activity != null) {
// activity.getConnection(error);
}
indiacatorDialog.dismiss();
}
});
ImageCacheManager.getInstance().getQueueForMainmenu().add(jsObjRequest);
}
}
private void indicatorAnim() {
if (indiacatorDialog != null) {
ImageView alertIndicator = (ImageView) indiacatorDialog.findViewById(R.id.alert_indicator);
alertIndicator.startAnimation(mRotateAnim);
if (!getActivity().isFinishing()) {
indiacatorDialog.show();
}
}
}
// Show alert for Time out
private void showPropertyIdTimeoutAlert(final Activity context) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setIcon(R.drawable.alert_dialog_icon);
alertDialog.setTitle(context.getString(R.string.timeout_msg));
alertDialog.setMessage(context.getString(R.string.timeout_msg2));
alertDialog.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
indicatorAnim();
// for property id
new CmsPropertyAsync(activity).execute(UCConstants.CMS_CONFIG_URL, UCConstants.CMS_CONFIG_KEY);
}
});
alertDialog.setNegativeButton("Cancel", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
getActivity().finish();
}
});
AlertDialog alert = alertDialog.create();
alert.setCancelable(false);
alert.setCanceledOnTouchOutside(false);
if (context != null && !context.isFinishing()) {
alert.show();
}
}
}
Actually, some data is being saved with onSavedInstaceState(). The data is not being deleted when process has been killed on LowMemory.
I fixed this with
#Override
protected void onSaveInstanceState(Bundle outState) {
//super.onSaveInstanceState(outState);
}
Just do not call super class. Just comment like above

Passing data to object in multiple fragments Android

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.

Categories

Resources