Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
alex gwartney
8,849 Pointsgetting a custom adapter in the main activity?
So i have played with this a bit but still can not get this idea to work. What i want to do is call my custom list adapter that i made in the main activity thread were im getting a json array. But since i was only able to learn how to pass the data through intents im not understanding how to just pass the data directly through the main activity would some one be able to explain how this is possible to do? The code i have so far is listed below any help will be much appreciated as i have been trying to get this to work for several days with out any luck.
public class MainActivity extends ActionBarActivity {
public String url = "http://blog.teamtreehouse.com/api/get_recent_summary/?count=20";
public static final String TAG = MainActivity.class.getSimpleName();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(isNetworkAvailable()) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
}
@Override
public void onResponse(Response response) throws IOException {
try {
String jsonData = response.body().string();
Log.v(TAG, jsonData);
if (response.isSuccessful()) {
getCurrentDetails(jsonData);
}
} catch (IOException e) {
Log.e(TAG, "Exception caught: ", e);
} catch (JSONException e) {
Log.e(TAG, "Exception caught: ", e);
}
}
});
}
}
private content[] getCurrentDetails(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
JSONArray data = forecast.getJSONArray("posts");
content[] myDataset = new content[data.length()];
for (int i = 0; i < data.length(); i++) {
JSONObject jsonDay = data.getJSONObject(i);
content day = new content();
day.setId(jsonDay.getInt("id"));
day.setUrl(jsonDay.getString("url"));
day.setTitle(jsonDay.getString("title"));
day.setDate(jsonDay.getString("date"));
day.setAuthor(jsonDay.getString("author"));
day.setThumbnail(jsonDay.getString("thumbnail"));
myDataset[i] = day;
}
return myDataset;
}
// This will check if there is a net work conection
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()) {
isAvailable = true;
}
return isAvailable;
}
}
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.HourViewHolder> {
private content[] mDataset;
public MyAdapter(content[] myDataset) {
mDataset = myDataset;
}
// the lay out is not the correct lay out but its just there for a example.
@Override
public HourViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.activity_main, parent, false);
HourViewHolder viewHolder = new HourViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(HourViewHolder holder, int position) {
holder.bindHour(mDataset[position]);
}
@Override
public int getItemCount() {
return mDataset.length;
}
public class HourViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView mTimeLabel;
public HourViewHolder(View itemView) {
super(itemView);
mTimeLabel = (TextView) itemView.findViewById(R.id.Title);
}
public void bindHour(content hour) {
mTimeLabel.setText(hour.getTitle());
}
@Override
public void onClick(View view) {
}
}
}
2 Answers
miguelcastro2
Courses Plus Student 6,573 PointsI recommend you continue on your studies to fully understand how asynchronous tasks work and Java in general.
Your main activity makes a request for JSON data and upon a response you can then create your list adapter. Take a look at this part of your code:
if (response.isSuccessful()) {
getCurrentDetails(jsonData);
}
At this point your asynchronous request was processed successfully and getCurrentDetails() will provide an array of content objects. Here is where you would create your adapter and pass in the content you created. You can pass in the content via constructor or setter method. You can also at this time provide feedback to the user if there was an issue fetching the JSON. Hope this helps :)
alex gwartney
8,849 PointsOhh see this makes so much more sense now of why my adapter was returning null thanks I will go and put this in. And see what happens thanks for the help
alex gwartney
8,849 Pointsalex gwartney
8,849 PointsI think one of the main issues i have had is not being able to pass the constructor method in the main activity when calling the adapter. It dosnt recognize it or something?