nmiltner nmiltner - 2 months ago 14
Android Question

RecyclerView Activity to Fragment

Im following a tutorial in on recyclerview found here http://javatechig.com/android/android-recyclerview-example

I have modified it to suit me needs, except for one thing, the MainActivity in this, I need to be in a fragment, not Activity. Here is my Fragment as it sits now:

public class FeedZooperListFragment extends Fragment {
private static final String TAG = "RecyclerViewExample";
private List<FeedZ> feedItemList = new ArrayList<FeedZ>();
//added static might remove
private static RecyclerView mRecyclerView;
private static MyRecyclerAdapter adapter;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

/* Allow activity to show indeterminate progress-bar */
getActivity().requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

setContentView(R.layout.fragment_recyclerview);

/* Initialize recycler view */
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
mRecyclerView.setLayoutManager(new GridLayoutManager(this,2));

/*Downloading data from below url*/
final String url = "http://www.thisismyurl.com";
new AsyncHttpTask().execute(url);
}

public class AsyncHttpTask extends AsyncTask<String, Void, Integer> {

/* @Override
protected void onPreExecute() {
setProgressBarIndeterminateVisibility(true);
}*/

@Override
protected Integer doInBackground(String... params) {
InputStream inputStream = null;
Integer result = 0;
HttpURLConnection urlConnection = null;

try {
/* forming th java.net.URL object */
URL url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();

/* for Get request */
urlConnection.setRequestMethod("GET");
int statusCode = urlConnection.getResponseCode();

/* 200 represents HTTP OK */
if (statusCode == 200) {
BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
response.append(line);
}

parseResult(response.toString());
result = 1; // Successful
}else{
result = 0; //"Failed to fetch data!";
}

} catch (Exception e) {
Log.d(TAG, e.getLocalizedMessage());
}
return result; //"Failed to fetch data!";
}

@Override
protected void onPostExecute(Integer result) {
// setProgressBarIndeterminateVisibility(false);
/* Download complete. Lets update UI */
if (result == 1) {
adapter = new MyRecyclerAdapter(FeedZListFragment.this, feedItemList);
mRecyclerView.setAdapter(adapter);
} else {
Log.e(TAG, "Failed to fetch data!");
}
}
}

private void parseResult(String result) {
try {
JSONObject response = new JSONObject(result);
JSONArray products = response.optJSONArray("products");

/*Initialize array if null*/
if (null == feedItemList) {
feedItemList = new ArrayList<FeedZ>();
}

for (int i = 0; i < products.length(); i++) {
JSONObject product = products.optJSONObject(i);

FeedZ item = new FeedZ();
item.setTitle(product.optString("title"));
item.setImage_url(product.optString("image_url"));
item.setPackage_url(product.optString("package_url"));
item.setIds(product.optString("ids"));
feedItemList.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}


My problems come with cannot resolve method setContentView(int) for
setContentView(R.layout.fragment_recyclerview)


as well as cannot resolve method findviewByID for

mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
mRecyclerView.setLayoutManager(new GridLayoutManager(this,2));


Any help is appreciated.

Answer

setContentView() is only in an Activity. You need to inflate the layout in the onCreateView() method that you will override.

public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_recyclerview,
        container, false);
} 

See here for more info on that - super.onCreateView in Fragments

For findViewById you can do one of 2 things -

You can write getActivity().findViewById()

or in the onCreateView method you can say:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
       View view =  inflater.inflate(R.layout.fragment_recyclerview,
            container, false)

      view.findViewById....

    return;
    }