0

I'm trying to get data from my server using JSON and put the retrieved data to arrays this is the fonction to retrieve category,intitule,id_news,images

public void getNewsFromServer(int beg){

    InputStream is = null;
    String result = "";

    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("beg", Integer.toString(beg)));

    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(strURL);
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
    } catch (Exception e) {
        Toast.makeText(context, e.toString(), Toast.LENGTH_LONG).show();
    }
    // conversion of the query into 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) {
        Toast.makeText(context, e.toString(),Toast.LENGTH_LONG).show();
    }

    try {
        JSONArray jArray = new JSONArray(result);
        for (int i = 0; i < jArray.length(); i++) {
            JSONObject json_data = jArray.getJSONObject(i);

            id_news[i] = Integer.toString(json_data.getInt("id_news"));
            categorie[i] = json_data.getString("categorie");
            intitule[i] = json_data.getString("intitule");
            image[i] = json_data.getString("image");
        }


    }catch (Exception e){
        Toast.makeText(context, e.toString(),
                Toast.LENGTH_LONG).show();
    }
}

And this the MainActivity.java

String [] id_news= new String [20];
String [] categorie= new String [20];
String [] intitule= new String [20];
String [] image= new String [20];

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...   
 try{
    //get data from the server and put it in tables
    getNewsFromServer(beg);
 }catch(NullPointerException e)
    {
        Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
        e.getStackTrace();
    }
}

but i always get NULLPointerException help please

these the logCat trace logCat

this the initialisation of the context Context context = this;

but it generate another exceptions NetworkOnMainThreadException and NullPointerException and JSONException:End of input at character 0..

Cœur
  • 37,241
  • 25
  • 195
  • 267
wael
  • 444
  • 4
  • 11

4 Answers4

2

The NPE comes from Toast initialization. Make sure the context you pass there is not null.

Since you use the toasts in exception catch blocks, log the exception stacktraces with e.g. e.printStackTrace() to get a hold on the root cause. (Prime suspect: NetworkOnMainThreadException)

For NetworkOnMainThreadException, do your network ops on a background thread. See How to fix android.os.NetworkOnMainThreadException? for more.

Community
  • 1
  • 1
laalto
  • 150,114
  • 66
  • 286
  • 303
0

In your call to Toast, the context variable is most likely null.

Never catch a NullPointerException. Make sure it never gets thrown.

Robby Pond
  • 73,164
  • 16
  • 126
  • 119
0

As laalto points out the NPE is coming in Toast statement.

Can you give a code snippet of how you have initialized context.

Also try using getActivity() there once and see if it solves the issue.

If it does then override onAttach() and initialize your context inside it. As directly giving getActivity() is not a good practice.

NetworkOnMainThreadException is caused because you should make network calls on a separate thread.
use something like:

Thread thread = new Thread()
{
    @Override
    public void run() {
        try {
           //your network calls here
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
};

thread.start();
KetanJogani
  • 306
  • 2
  • 20
0

i fixe the problem by using the AsynkTask

private class Asyn_GetNewsFromServer extends AsyncTask<Void, Void, Void> {
    @Override
    protected Void doInBackground(Void... params) {
        getNewsFromServer(beg);
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
                    //do what ever you want
    }
}

thx for your help

wael
  • 444
  • 4
  • 11