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

Android Build a Weather App (2015) Hooking Up the Model to the View Wrapping Up

Chandrashekhar singh
Chandrashekhar singh
35 Points

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.csing1s.news.NewsData.getTitle()

I am working on news api but i am not able to run this on my mobile

Here is my coding package com.csing1s.news;

import android.app.ListActivity; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.util.Log; import android.widget.Toast;

import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response;

public class MainActivity extends ListActivity { public static final String TAG = MainActivity.class.getSimpleName(); // private TextView mTextView; // for news title // private TextView description; // news description; private NewsData mData; private Forcast mForcast = new Forcast(); private NewsData[] newsDatas; //= new NewsData[100]; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getNews();

    Log.d(TAG, "UI is working dont worry!");
  //  mTextView = (TextView) findViewById(R.id.Title);
  //  description = (TextView) findViewById(R.id.Description);
    NewsAdapter mNews = new NewsAdapter(this,newsDatas);
     setListAdapter(mNews);

}
public void getNews()
{
    String api ="83b20969c34c4f4390afe507dbabb7d9";
    String newsurl ="https://newsapi.org/v1/articles?source=techcrunch&apiKey=83b20969c34c4f4390afe507dbabb7d9";
    if(IsNetworkAvailabel())
    {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(newsurl).build();
        okhttp3.Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                    }
                });
                AlertUserError();
            }



            @Override
            public void onResponse(Call call, Response response) throws IOException {
              runOnUiThread(new Runnable() {
                  @Override
                  public void run() {

                  }
              });
                try{
                    String newsjasondata = response.body().string();
                    Log.v(TAG,newsjasondata);
                    if(response.isSuccessful())
                    {
                        mForcast= parseforcat(newsjasondata);



                    }

                }
                catch (IOException e)
                {
                    Log.e(TAG,"Exception Caught",e);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

    }
    else
    {
        Toast.makeText(this,"Opps Network is not available ",Toast.LENGTH_SHORT).show();
    }


}

private Forcast parseforcat(String newsjasondata) throws JSONException {
    Forcast forcast = new Forcast();
    forcast.setNewsDatas(getNewsDatas(newsjasondata));
    return forcast;
}

private void AlertUserError() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Error");
    builder.setCancelable(true);
}

private boolean IsNetworkAvailabel() {
    ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo network = manager.getActiveNetworkInfo();
    boolean isAvailable =false;
    if(network !=null && network.isConnected())
    {
        isAvailable =true;
    }
    return isAvailable;
}

public NewsData[] getNewsDatas(String newsjasondata) throws JSONException
{
    JSONObject jsonObject = new JSONObject(newsjasondata);
    JSONArray article =  jsonObject.getJSONArray("articles");
    NewsData[]newsDatas = new NewsData[article.length()];
    for( int i =0; i<article.length();i++)
    {
           JSONObject object =  article.getJSONObject(i);
         NewsData newsData = new NewsData();
         newsData.setDescription(object.getString(" description "));
          newsData.setTitle(object.getString(" title "));
        newsDatas[i] = newsData;

    }


   return newsDatas;
}
/*

public NewsData[] getnewss(String newsjasondata) throws JSONException { JSONObject jsonObject = new JSONObject(newsjasondata); JSONArray article = jsonObject.getJSONArray("articles"); NewsData[] newsDatas = new NewsData[article.length()]; for (int i = 0; i < article.length(); i++) { JSONObject object = article.getJSONObject(i); NewsData newsData = new NewsData(); newsData.setDescription(object.getString("description")); newsData.setTitle(object.getString("title")); newsDatas[i] = newsData;

   }


   return newsDatas;

} */ }

//This is my forcast class public class Forcast { private NewsData[]mNewsDatas;

public NewsData[] getNewsDatas() {
    return mNewsDatas;
}

public void setNewsDatas(NewsData[] newsDatas) {
    mNewsDatas = newsDatas;
}

} //This is my Newsdataclass public class NewsData { private String title; private String description;

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}

} //this is my 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;

/**

  • Created by Csing1s on 11/12/2016. */ public class NewsAdapter extends BaseAdapter {

private Context mContext; private NewsData[] mNewsDatas;

public NewsAdapter(Context context, NewsData[] news)
{
   this.mContext =context;
   this.mNewsDatas=news;
}



@Override

public int getCount() { return mNewsDatas.length; }

@Override
public Object getItem(int position) {
    return mNewsDatas[position];
}

@Override
public long getItemId(int position) {
    return 0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder mviewholder;
              if(convertView==null)
              {
                  convertView = LayoutInflater.from(mContext).inflate(R.layout.newslist,null);
                  mviewholder = new ViewHolder();
                  mviewholder.mDescription = (TextView) convertView.findViewById(R.id.Descriptionlabel);
                  mviewholder.mTitle = (TextView) convertView.findViewById(R.id.Titlebar);
                  convertView.setTag(mviewholder);

              }
             else
              {
                  mviewholder = (ViewHolder) convertView.getTag();

              }
                NewsData data = mNewsDatas[position];

                mviewholder.mTitle.setText(data.getTitle());
                mviewholder.mDescription.setText(data.getDescription());

      return convertView;
}
private static class ViewHolder
{
 public TextView mTitle;
   public TextView mDescription;
}

}

1 Answer

Seth Kroger
Seth Kroger
56,413 Points

Because you're getting the news asynchronously but setting up the adapter immediately, there will be a bit of time where the list will be empty. You need to make sure the adapter can handle that situation, and has the ability to update the like when the news does come in. (basically a method to set the list to the new one and call notifyDatasetChanged(), which tells the adapter to update)

Chandrashekhar singh
Chandrashekhar singh
35 Points

I am sorry i did not get you can you explain me , where should i put this function