Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9110403
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T03:15:39+00:00 2026-06-17T03:15:39+00:00

I have the following classes: Main.java package com.example.webapp; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity;

  • 0

I have the following classes:

Main.java

package com.example.webapp;

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

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.Time;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;

public class Main extends Activity {


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.settings:
                showSettings();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    final Handler handler = new Handler()
    {
        public void handleMessage(Message msg) 
        {

            try {
                final String result = msg.toString();
                JSONObject jObject  = new JSONObject(result.toString());
                mainView(jObject);
              }
              catch(JSONException e) {
                e.getCause();
              }


        };
    };

    public void mainView(JSONObject result){

    }

    public void showSettings(){
        setContentView(R.layout.settings);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d("Oncreate","1");
        String url = "http://xxx.xxx.xxx/webapp/server.php?method=getPageIndexLiveValues";
        Log.d("Oncreate","2");
        JSONhandler parser = new JSONhandler(this);
        parser.execute(url);

        Log.d("Oncreate","3");



    }


        public void onRequestCompleted(JSONObject result) {
            setContentView(R.layout.main);
           Log.d("onRequestComplete","complete");
            try {
                TextView test1 = (TextView) findViewById(R.id.textView1);
                test1.setText(result.getString("GP").toString()+"W");
                TextView test2 = (TextView) findViewById(R.id.textView2);
                test2.setText(result.getString("IP").toString()+"W");
                TextView test3 = (TextView) findViewById(R.id.textView3);
                test3.setText(result.getString("EFF").toString()+"%");

                Time today = new Time(Time.getCurrentTimezone());
                today.setToNow();


                TextView textViewDay = (TextView) findViewById(R.id.textDateTime);

                textViewDay.setText(today.monthDay+"-"+(today.month+1)+"-"+today.year+" "+today.format("%k:%M:%S"));             // Day of the month (0-31)

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }



}

JSONhandler.java
package com.example.webapp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.util.Log;

public class JSONhandler extends AsyncTask<String, Void, JSONObject> {

    //private static final JSONObject JSONObject = null;
    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    public JSONhandler(Main main){

    }

    public interface MyCallbackInterface {
        public void onRequestCompleted(JSONObject json);
    }

    private MyCallbackInterface mCallback;

    public void JSONParser(MyCallbackInterface callback) {
        mCallback = callback;
    }

    public JSONObject getJSONFromUrl(String url) { 
        Log.d("getJSONFromUrl","1");        
        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();           

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        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();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;


    }

    @Override
    protected JSONObject doInBackground(String... params) {
        Log.d("doInBackground","1");
        String url = params[0];
        Log.d("doInBackground",url);
        Log.d("doInBackground","2");
        return getJSONFromUrl(url);
    }

    @Override
    protected void onPostExecute(JSONObject result) {
        super.onPostExecute(result);
        Log.d("onPostExecute",result.toString());

        //In here, call back to Activity or other listener that things are done
        try{
            JSONObject json = result.getJSONObject("sumIn");
            Log.d("onPostE Sum",json.toString());
            mCallback.onRequestCompleted(json); //<<<<<< See bel
        }catch(JSONException e){
            Log.d("onPostE Sum",json.toString());
        }
    }
}

!!!!ERROR MESSAGE!!!!
E/AndroidRuntime(2237): FATAL EXCEPTION: main
E/AndroidRuntime(2237): java.lang.NullPointerException
E/AndroidRuntime(2237):     at com.example.webapp.JSONhandler.onPostExecute(JSONhandler.java:107)
E/AndroidRuntime(2237):     at com.example.webapp.JSONhandler.onPostExecute(JSONhandler.java:1)
and a lot more.....

I’m very new to Java/Android and can’t figure out whats happening here.
Hope some one can help me.

UPDATED CODE:
I updated the code, but still get the error on Line 107 (//<<<< see below).
When json is initialized correct, the code runs in the mCallback error.
When json is null, the TryCatch catches the error and logs “empty”.

The new code for Main and change the code on suggestion of Sam.

package com.example.webapp;

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

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.Time;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;

import com.example.webapp.JSONhandler.MyCallbackInterface;

    public class Main extends Activity implements MyCallbackInterface  {


        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle item selection
        switch (item.getItemId()) {
            case R.id.settings:
                showSettings();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    final Handler handler = new Handler()
    {
        public void handleMessage(Message msg) 
        {

            try {
                final String result = msg.toString();
                JSONObject jObject  = new JSONObject(result.toString());
                mainView(jObject);
              }
              catch(JSONException e) {
                e.getCause();
              }


        };
    };

    public void mainView(JSONObject result){

    }

    public void showSettings(){
        setContentView(R.layout.settings);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d("Oncreate","1");
        String url = "http://xxx.xxx.xxx";
        Log.d("Oncreate","2");
        JSONhandler parser = new JSONhandler(this);
        parser.execute(url);

        Log.d("Oncreate","3");



    }

    @Override
    public void onRequestCompleted(JSONObject result) {
        setContentView(R.layout.main);
        Log.d("onRequestComplete","complete");
            try {
                TextView test1 = (TextView) findViewById(R.id.textView1);
                test1.setText(result.getString("GP").toString()+"W");
                TextView test2 = (TextView) findViewById(R.id.textView2);
                test2.setText(result.getString("IP").toString()+"W");
                TextView test3 = (TextView) findViewById(R.id.textView3);
                test3.setText(result.getString("EFF").toString()+"%");

                Time today = new Time(Time.getCurrentTimezone());
                today.setToNow();


                TextView textViewDay = (TextView) findViewById(R.id.textDateTime);

                textViewDay.setText(today.monthDay+"-"+(today.month+1)+"-"+today.year+" "+today.format("%k:%M:%S"));             // Day of the month (0-31)

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }



}

The new code for JSONhandler and change the code on suggestion of Sam.

package com.example.webapp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.util.Log;

public class JSONhandler extends AsyncTask<String, Void, JSONObject> {

    //private static final JSONObject JSONObject = null;
    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    public JSONhandler(Main main){

    }

    public interface MyCallbackInterface {
        public void onRequestCompleted(JSONObject json);
    }

    private MyCallbackInterface mCallback;

    public JSONhandler(MyCallbackInterface callback) {
        mCallback = callback;
    }

    public JSONObject getJSONFromUrl(String url) { 
        Log.d("getJSONFromUrl","1");        
        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();           

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        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();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;


    }

    @Override
    protected JSONObject doInBackground(String... params) {
        Log.d("doInBackground","1");
        String url = params[0];
        Log.d("doInBackground",url);
        Log.d("doInBackground","2");
        return getJSONFromUrl(url);
    }

    @Override
    protected void onPostExecute(JSONObject result) {
        super.onPostExecute(result);
        Log.d("onPostExecute",result.toString());

        //In here, call back to Activity or other listener that things are done
        try{
            JSONObject json = result.getJSONObject("sumInvrters");
            Log.d("onPostE Sum",json.toString());
            mCallback.onRequestCompleted(json); //<<<< see below 
        }catch(JSONException e){
            Log.d("onPostE Sum","empty");
        }
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-17T03:15:40+00:00Added an answer on June 17, 2026 at 3:15 am

    With the LogCat and your note:

    mCallback.onRequestCompleted(json); //<<<<<< See bel
    

    It appears mCallback is null, since you forgot to define it. Let’s change things around a little:

    1. Have your Activity implement your callback:

      public class Main extends Activity implements MyCallbackInterface {
      

      And add @Override to onRequestCompleted() if necessary.

    2. Remove the JSONhandler constructor that expects an Activity and replace it with one that expects your interface.


      So remove this code:

      public JSONhandler(Main main){
      
      }
      
      public void JSONParser(MyCallbackInterface callback) {
          mCallback = callback;
      }
      


      Use this constructor instead:

      public JSONhandler(MyCallbackInterface callback) {
          mCallback = callback;
      }
      

    Now this code should work just fine:

    JSONhandler parser = new JSONhandler(this);
    parser.execute(url);
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Example: For(int i=0; i<4; i++) playSound(Sound.wav); I have the following classes: Main import java.io.IOException;
I have the following directory structure: C:\CheckinProject\sources\main\EmailProcessor.java<br/> \compile-and-run.bat<br/> \classes\main\EmailProcessor.class The file EmailProcessor.java contains this:
I have following classses Hello.java package speak.hello; import java.util.Map; import speak.hi.CustomMap; import speak.hi.Hi; public
I have Java classes with the following structure (the class names do not imply
I have the following directory structure. src| |pack| |Test.java data| |data.txt classes| |pack| |Test.class
I have 2 classes, WordSearch.java is where all the main code is held and
I have the following classes: package models; public class Test extends activejdbc.Model { }
Let's say, I have the following structure: src.main.java first one.java two.java three.java second alpha.java
I have following classes : Emp.java final public class Emp { private Integer id;
I have an Eclipse project with the following directory structure: MyProj >> src/main/java >>

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.