2

I want to start an activity and give out a Toast message after I parsed a JSON response.

public class Sign_Up extends AppCompatActivity {

  ....

  register();


  public void register()
  {
  final String url = "someURL";

        new Json().checkJsonFile(url,getApplicationContext());
  }

  //Now in an non-activity

  public class Json {

    public void checkJsonFile(final String url, final Context context) {

        new Thread(new Runnable() {
            public void run() {
                String result;
                String line;

                try {

                    URL obj = new URL(url);
                    HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
                    conn.setReadTimeout(5000);
                    conn.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
                    conn.addRequestProperty("User-Agent", "Mozilla");
                    conn.addRequestProperty("Referer", "google.com");


                    boolean redirect = false;

                    // normally, 3xx is redirect
                    int status = conn.getResponseCode();
                    if (status != HttpURLConnection.HTTP_OK) {
                        if (status == HttpURLConnection.HTTP_MOVED_TEMP
                                || status == HttpURLConnection.HTTP_MOVED_PERM
                                || status == HttpURLConnection.HTTP_SEE_OTHER)
                            redirect = true;
                    }

                    if (redirect) {

                        // get redirect url from "location" header field
                        String newUrl = conn.getHeaderField("Location");

                        // get the cookie if need, for login
                        String cookies = conn.getHeaderField("Set-Cookie");

                        // open the new connnection again
                        conn = (HttpURLConnection) new URL(newUrl).openConnection();
                        conn.setRequestProperty("Cookie", cookies);
                        conn.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
                        conn.addRequestProperty("User-Agent", "Mozilla");
                        conn.addRequestProperty("Referer", "google.com");


                    }

                    BufferedReader in = new BufferedReader(
                            new InputStreamReader(conn.getInputStream()));

                    StringBuilder sb = new StringBuilder();

                    while ((line = in.readLine()) != null) {
                        sb.append(line);

                    }
                    in.close();

                    result = sb.toString();

                    new Sign_Up().parseJSON(result);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}


        //Back in Sign_Up class

        public void parseJSON(String JSON){
        int error = -1;
        try {
                JSONObject jsonObject = new JSONObject(JSON);

                error = Integer.parseInt(jsonObject.getString("error_code"));

        } catch (JSONException e) {
            //Retry
            register();

            e.printStackTrace();
        }

        progressDialog.dismiss();

        switch (error) {
            case 0: //Successful
                finish();
                startActivity(new Intent(Sign_Up.this, Loading.class));
                break;
            case 1:
                Toast.makeText(getApplicationContext(), "blabla", Toast.LENGTH_SHORT).show();
                break;
            case 2:
                Toast.makeText(getApplicationContext(), "other blabla", Toast.LENGTH_SHORT).show();
                break;
            default:
                register();
                break;
        }
    }

However, when I put the Json stuff inside the Sign_Up class at least the startActivity works, but the Toast doesn't. As well, I would like to have the Json stuff in an seperate class.

Thank you very much in advance!

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Tester2
  • 57
  • 1
  • 9

1 Answers1

0

You cannot create an Activity by calling

new MyActivity()

and expect anything to work. The line

new Sign_Up().parseJSON(result);

is creating a new instance of the Sign_Up activity improperly, so it is not bound to a context and none of its lifecycle calls will be executed. You can't show a Toast in that state.

A better solution would be to pass an interface from Sign_Up into the Json class to let it call back to the original Sign_Up instance rather than trying to make a new instance. For example:

class Json {
    public interface Callback {
        public void run(String result);    
    }

    private Callback callback

    Json(Callback c) {
        callback = c;
    }

    // later, replace new Sign_Up().parseJSON(result) with callback.run(result)
}

and to create it replace

new Json().checkJsonFile(url,getApplicationContext());

with

new Json(new Json.Callback() {
    @Override
    public void run(String result) {
        parseJSON(result);
    }
}).checkJsonFile(url,getApplicationContext());

You'll also want to make sure that all UI operations (toast generation) are being run on the UI thread.

Tyler V
  • 9,694
  • 3
  • 26
  • 52
  • Very awesome! I've thought about that stuff, but wanted to be sure and asked here before. Thank you very much :) – Tester2 Jul 30 '18 at 00:37
  • Hi Tyler, could you maybe have a look on this as well, would really appreciate it :) https://stackoverflow.com/questions/51662401/getstring-and-dialoglistener-doesnt-work-after-class-switch – Tester2 Aug 02 '18 at 21:31