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
JIHOON JUNG
10,927 Pointsjava.lang.NullPointerException BaseAdapter
package com.oikostuio.newsapp.ui;
import android.app.ListActivity; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast;
import com.oikostuio.newsapp.R; import com.oikostuio.newsapp.adapter.NewsAdapter; import com.oikostuio.newsapp.news.CurrentStatus; import com.oikostuio.newsapp.news.Doc; import com.oikostuio.newsapp.news.News; import com.squareup.okhttp.Call; import com.squareup.okhttp.Callback; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.Response;
import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject;
import java.io.IOException;
import butterknife.ButterKnife; import butterknife.InjectView;
public class MainActivity extends ListActivity {
public static final String TAG = MainActivity.class.getSimpleName();
private News mNews;
public Doc[] mDocsToAdapter;
private ListView newsListView;
@InjectView(R.id.statusValue) TextView mStatusValue;
@InjectView(R.id.refreshImageView) ImageView mRefreshImageView;
@InjectView(R.id.progressBar) ProgressBar mProgressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
mProgressBar.setVisibility(View.INVISIBLE);
mRefreshImageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getNews();
}
});
getNews();
Log.d(TAG, "Main UI code is running!");
newsListView = (ListView) findViewById(android.R.id.list);
displayNews();
}
public void displayNews() {
getIntent();
NewsAdapter adapter = new NewsAdapter(this, mDocsToAdapter);
newsListView.setAdapter(adapter);
}
private void getNews() {
String newsUrl = "http://api.nytimes.com/svc/search/v2/articlesearch.json?api-key=sample-key";
if (isNetworkAvailable()) {
toggleRefresh();
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(newsUrl)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
runOnUiThread(new Runnable() {
@Override
public void run() {
toggleRefresh();
}
});
alertUserAboutError();
}
@Override
public void onResponse(Response response) throws IOException {
runOnUiThread(new Runnable() {
@Override
public void run() {
toggleRefresh();
}
});
try {
String jsonData = response.body().string();
Log.v(TAG, jsonData);
if (response.isSuccessful()) {
mNews = parseForcecastDetails(jsonData);
runOnUiThread(new Runnable() {
@Override
public void run() {
updateDisplay();
}
});
} else {
alertUserAboutError();
}
}
catch (IOException e) {
Log.e(TAG, "Exception caught: ", e);
}
catch (JSONException e) {
Log.e(TAG, "Exception caught: ", e);
}
}
});
}
else {
Toast.makeText(this, getString(R.string.network_unavailable_message),
Toast.LENGTH_LONG).show();
}
}
private void toggleRefresh() {
if (mProgressBar.getVisibility() == View.INVISIBLE) {
mProgressBar.setVisibility(View.VISIBLE);
mRefreshImageView.setVisibility(View.INVISIBLE);
}
else {
mProgressBar.setVisibility(View.INVISIBLE);
mRefreshImageView.setVisibility(View.VISIBLE);
}
}
private void updateDisplay() {
CurrentStatus currentStatus = mNews.getCurrentStatus();
mStatusValue.setText(currentStatus.getKEY_STATUS());
}
private News parseForcecastDetails(String jsonData) throws JSONException {
News news = new News();
news.setCurrentStatus(getCurrentDetails(jsonData));
news.setDailyNews(getDailyNews(jsonData));
return news;
}
private Doc[] getDailyNews(String jsonData) throws JSONException {
JSONObject news = new JSONObject(jsonData);
String status = news.getString("status");
JSONObject response = news.getJSONObject("response");
JSONArray docsInJSON = response.getJSONArray("docs");
Doc[] docs = new Doc[docsInJSON.length()];
for(int i = 0; i < docsInJSON.length(); i++) {
JSONObject jsonResult = docsInJSON.getJSONObject(i);
JSONObject headline = jsonResult.getJSONObject("headline");
String main = headline.getString("main");
Doc docFromNews = new Doc();
docFromNews.setWebUrl(jsonResult.getString("web_url"));
docFromNews.setSnippet(jsonResult.getString("snippet"));
docFromNews.setPubDate(jsonResult.getString("pub_date"));
docFromNews.setSection(jsonResult.getString("section_name"));
docFromNews.setSource(jsonResult.getString("source"));
docFromNews.setKEY_STATUS(status);
docFromNews.setHeadline(main);
docs[i] = docFromNews;
}
return docs;
}
private CurrentStatus getCurrentDetails(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
String status = forecast.getString("status");
Log.i(TAG, "From JSON: " + status);
CurrentStatus currentStatus = new CurrentStatus();
currentStatus.setKEY_STATUS(status);
return currentStatus;
}
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;
}
private void alertUserAboutError() {
AlertDialogFragment dialog = new AlertDialogFragment();
dialog.show(getFragmentManager(), "error_dialog");
}
}
package com.oikostuio.newsapp.adapter;
import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView;
import com.oikostuio.newsapp.R; import com.oikostuio.newsapp.news.Doc;
/**
-
Created by jeonhonlee on 5/22/15. */ public class NewsAdapter extends BaseAdapter {
private Context mContext; private Doc[] mDocs;
public NewsAdapter(Context context, Doc[] docs) { mContext = context; mDocs = docs; }
@Override public int getCount() { return mDocs.length; }
@Override public Object getItem(int position) { return mDocs[position]; }
@Override public long getItemId(int position) { return position; }
@Override public View getView(int position, View convertView, ViewGroup parent) { final ViewHolder holder;
if(convertView == null) { // brand now convertView = LayoutInflater.from(mContext).inflate(R.layout.news_list_item, null); holder = new ViewHolder(); holder.sectionLabel = (TextView) convertView.findViewById(R.id.sectionLabel); holder.mainLabel = (TextView) convertView.findViewById(R.id.mainLabel); holder.sourceLabel = (TextView) convertView.findViewById(R.id.sourceLabel); holder.pubDateLabel = (TextView) convertView.findViewById(R.id.pubDateLabel); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } Doc doc = mDocs[position]; holder.mainLabel.setText(doc.getHeadline()); holder.pubDateLabel.setText(doc.getPubDate()); holder.sectionLabel.setText(doc.getSection()); holder.sourceLabel.setText(doc.getSource()); return convertView;
}
private static class ViewHolder {
TextView sectionLabel; TextView mainLabel; TextView sourceLabel; TextView pubDateLabel;
}
}
package com.oikostuio.newsapp.news;
/**
-
Created by jeonhonlee on 5/22/15. */ public class News {
private CurrentStatus mCurrentStatus; private Doc[] mDailyNews;
public Doc[] getDailyNews() { return mDailyNews; }
public void setDailyNews(Doc[] dailyNews) { mDailyNews = dailyNews; }
public CurrentStatus getCurrentStatus() { return mCurrentStatus; }
public void setCurrentStatus(CurrentStatus currentStatus) { mCurrentStatus = currentStatus; }
}
private String KEY_STATUS;
public String getKEY_STATUS() {
return KEY_STATUS;
}
public void setKEY_STATUS(String KEY_STATUS) {
this.KEY_STATUS = KEY_STATUS;
}
package com.oikostuio.newsapp.news;
/**
-
Created by jeonhonlee on 5/21/15. */ public class Doc {
private String mWebUrl; // web_url private String mSnippet; // snippet private String mPubDate; // pub_date private String mSource; // source private String mSection; // section_name private String KEY_STATUS; // status private String mHeadline; // Headline
public String getHeadline() { return mHeadline; }
public void setHeadline(String headline) { mHeadline = headline; }
public String getKEY_STATUS() { return KEY_STATUS; }
public void setKEY_STATUS(String KEY_STATUS) { this.KEY_STATUS = KEY_STATUS; }
public String getWebUrl() { return mWebUrl; }
public void setWebUrl(String webUrl) { mWebUrl = webUrl; }
public String getSnippet() { return mSnippet; }
public void setSnippet(String snippet) { mSnippet = snippet; }
public String getPubDate() { return mPubDate; }
public void setPubDate(String pubDate) { mPubDate = pubDate; }
public String getSource() { return mSource; }
public void setSource(String source) { mSource = source; }
public String getSection() { return mSection; }
public void setSection(String section) { mSection = section; } }
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.oikostuio.newsapp/com.oikostuio.newsapp.ui.MainActivity}: java.lang.NullPointerException at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084) at android.app.ActivityThread.access$600(ActivityThread.java:130) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:137) at android.app.ActivityThread.main(ActivityThread.java:4745) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:511) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) at dalvik.system.NativeStart.main(Native Method) Caused by: java.lang.NullPointerException at com.oikostuio.newsapp.adapter.NewsAdapter.getCount(NewsAdapter.java:28) at android.widget.ListView.setAdapter(ListView.java:460) at com.oikostuio.newsapp.ui.MainActivity.displayNews(MainActivity.java:76) at com.oikostuio.newsapp.ui.MainActivity.onCreate(MainActivity.java:69) at android.app.Activity.performCreate(Activity.java:5008) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084) at android.app.ActivityThread.access$600(ActivityThread.java:130) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:137) at android.app.ActivityThread.main(ActivityThread.java:4745) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:511) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) at dalvik.system.NativeStart.main(Native Method)
1 Answer
JIHOON JUNG
10,927 PointsPlease help me, I'm stuck in this code for 2 days
JIHOON JUNG
10,927 PointsJIHOON JUNG
10,927 Pointsat com.oikostuio.newsapp.adapter.NewsAdapter.getCount(NewsAdapter.java:28)
===