0

I want to get a JSON response from a php displayed in a TextView in Android Studio. I now have this code to do that, but it doesn't work. As far as I can see it doesn't even run when the app is opened.

public class MainActivity extends Activity {

private SQLiteHandler db;
private SessionManager session;

private String readAll(Reader rd) throws IOException {
    StringBuilder sb = new StringBuilder();
    int cp;
    while ((cp = rd.read()) != -1) {
        sb.append((char) cp);
    }
    return sb.toString();
}

public JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
    InputStream is = new URL(url).openStream();
    try {
        BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
        String jsonText = readAll(rd);
        JSONObject json = new JSONObject(jsonText);
        return json;
    } finally {
        is.close();
    }
}

public void main(String[] args) throws IOException, JSONException {
    TextView txtUser = (TextView) findViewById(R.id.user);
    JSONObject json = readJsonFromUrl("http://piggybank.wordmediavormgever.nl/getSaldo.php");
    System.out.println(json.toString());
    System.out.println(json.getString("saldo"));
    try {
        JSONObject jsonObject = new JSONObject();
        String response = jsonObject.getString("saldo");
        txtUser.setText(response);

    } catch (JSONException e) {

        e.printStackTrace();
    }
}

Can anyone see what I'm doing wrong? The response from the url is {"saldo":783}.

5
  • you are trying to start an android activity with a main method? Commented Sep 6, 2017 at 6:29
  • I just got this piece of code from this site, I'm not very experienced with coding myself (yet) Commented Sep 6, 2017 at 6:31
  • Java or Android ? for Android see those: stackoverflow.com/questions/33229869/… and stackoverflow.com/questions/13196234/… Commented Sep 6, 2017 at 6:31
  • Java in Android Studio Commented Sep 6, 2017 at 6:34
  • You can check my answer.@Roan Commented Sep 6, 2017 at 6:46

2 Answers 2

1

Try it!

remove

   JSONObject jsonObject = new JSONObject();

And use

   JSONObject json = readJsonFromUrl("http://piggybank.wordmediavormgever.nl/getSaldo.php");
  try {
    String response = json.getString("saldo");
    Log.e("AAAAAAAAA %s", response);

} 

You must call it in AsyncTask. Completed code!!!

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_test2);
    new GetDataSync().execute();
}

String saldo = "";

public class GetDataSync extends AsyncTask<Void, Void, Void> {


    @Override
    protected Void doInBackground(Void... params) {
        try {
            getData();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        txtUser.setText(saldo);
    }
}

private void getData() throws IOException, JSONException {
    JSONObject json = readJsonFromUrl("http://piggybank.wordmediavormgever.nl/getSaldo.php");
    try {
        String response = json.getString("saldo");
        Log.e("AAAAAAAAA %s", response);
        saldo = response;

    } catch (JSONException e) {

        e.printStackTrace();
    }
}

private String readAll(Reader rd) throws IOException {
    StringBuilder sb = new StringBuilder();
    int cp;
    while ((cp = rd.read()) != -1) {
        sb.append((char) cp);
    }
    return sb.toString();
}

public JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
    InputStream is = new URL(url).openStream();
    try {
        BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
        String jsonText = readAll(rd);
        JSONObject json = new JSONObject(jsonText);
        return json;
    } finally {
        is.close();
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

The ButterKnife.bind thing, what is that for? Cannot resolve symbol 'ButterKnife'
Okay, if I run this code I get this response in the Android Monitor: E/AAAAAAAAA %s: 0. Nothing else happens, And it isn't setting the text in the TextView.
You get completed data from server. You set it to TextView.
Yes, the code works now, thanks! But now I have a new problem. When I login with my app it doens't remember I'm logged in. So the server gives as response 0. Is there an easy way to solve this?
This can not be resolved with all the information above. You need to add the source code
1

I think the problem is here in main function in try block

JSONObject jsonObject = new JSONObject();
String response = jsonObject.getString("saldo");
txtUser.setText(response);

your jsonObject is empty You should call

String response = json.getString("saldo");
txtUser.setText(response);

One more thing when you are making some network call you should do it in background thread , not on UI thread.(readJsonFromUrl method should be called in background thread)

as Nguyễn Trung Hiếu's answer suggested

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.