2

I have JSON parser class with a static jsonString variable I have this code in the class:

public class JSONParser extends AsyncTask <String, String , String> {

@Override
protected String doInBackground(String... params) {

    HttpURLConnection httpConnection = null;      
    BufferedReader reader = null;      
    StringBuffer buffer = new StringBuffer();
    try {

        URL url = new URL(params[0]);                
        httpConnection = (HttpURLConnection) url.openConnection();
        httpConnection.connect();
        InputStream stream = httpConnection.getInputStream();
        reader = new BufferedReader(new InputStreamReader(stream));
        String line = "";
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }
        return buffer.toString();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }        
    finally {
        if (httpConnection != null)
            httpConnection.disconnect();          
        try {
            if (reader != null)
                reader.close();               
        } catch (IOException e) {
            e.printStackTrace();
        }        }
    return "no Json";    }

@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);
    str = result;        
    try {
        JSONObject jObject = new JSONObject(result);
        aJsonString = jObject.getString("country");
        Log.e("JSON OBJECT" , aJsonString);
    } catch (JSONException e) {
        e.printStackTrace();

but in the MainActivity when I'm trying:

 public TextView tvJsonItem;
        tvJsonItem = (TextView) findViewById(R.id.tvJsonItem);
        final ImageView imageView = (ImageView) findViewById(R.id.imageView);
        Button btnHit= (Button) findViewById(R.id.btnHit);
        assert btnHit != null;
        btnHit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

               new JSONParser().execute("http://ip-api.com/json");
                tvJsonItem.setText(JSONParser.str);    
                if (JSONParser.aJsonString.isEmpty()){
                    Toast.makeText(MainActivity.this ,"No Json" , Toast.LENGTH_SHORT).show();
                }

                else if (JSONParser.aJsonString.contains("Israel"))
                {
                    Toast.makeText(MainActivity.this ,JSONParser.aJsonString , Toast.LENGTH_SHORT).show();
                    assert imageView != null;
                    imageView.setImageResource(R.drawable.israel);
                }
            }
        });
    }
}Toast.LENGTH_SHORT).show();
        assert imageView != null;
        imageView.setImageResource(R.drawable.uk);
    }

The Main crashes, and complains about nullpointerexception why?

Amit Vaghela
  • 22,772
  • 22
  • 86
  • 142

0 Answers0