2

I've been at this for some time now, and I'm stuck.. I've made the code below to get one variable from JSON, and display it on screen in a textview. The app doesn't crash, but it always displays IT DISPLAYS THIS!!.. (see code). I can't figure out why it doesn't show the text.. It should display naam from here..

package me.janvandijk.receptenapp;


public class Recept extends Activity {

    String receptid;
    String result;
    TextView receptTitel;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recept);

    receptid = getIntent().getStringExtra("receptid");
    receptTitel = (TextView)findViewById(R.id.receptTitel);

    //First Initialise TextView
    getMethod method=new getMethod();
    try {
        result = method.getInternetData();// Then get the Json response
    } catch (Exception e) {
        receptTitel.setText("IT DISPLAYS THIS!!..");
        e.printStackTrace();
    }

    try{
        JSONObject json=new JSONObject(result);
        try {
            String receptNaam =json.getString("naam");
            receptTitel.setText(receptNaam);
        } catch (JSONException e) {
            e.printStackTrace();
            receptTitel.setText("Never Seen This..");
        }

    }
    catch (JSONException e) {
        e.printStackTrace();
    }
    catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    //new ReceptAsynTask().execute("http://janvandijk.me/zooi/receptenapp/getrecipes.php?type=request&datatype=recept&id=" + receptid);



   public void setText(String string){
        //tv.setText(string);
    }

    public void showToast(){
        Toast.makeText(getApplicationContext(), "Bezig met laden recept met ID "+receptid, Toast.LENGTH_LONG).show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_recept, menu);
        //TextView view = (TextView) findViewById(R.id.testje);
        //view.setText(receptid);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}


public class getMethod {

    public String getInternetData() throws Exception {
        BufferedReader in = null;
        String data = null;
        try {
            HttpClient client = new DefaultHttpClient();
            URI website = new URI("http://janvandijk.me/zooi/receptenapp/getrecipes.php?type=request&datatype=recept&id=1");

            HttpGet request = new HttpGet();
            request.setURI(website);
            HttpResponse response = client.execute(request);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer sb = new StringBuffer("");
            String l = "";
            String nl = System.getProperty("line.separator");
            while ((l = in.readLine()) !=null) {
                sb.append(l + nl);
            }

            in.close();
            data = sb.toString();
            return data;
        }
        finally {
            if (in !=null){
                try{
                    in.close();
                    return data;
                }catch (Exception e){
                    e.printStackTrace();

                }
            }

        }
    }
}
fractalwrench
  • 4,028
  • 7
  • 33
  • 49

2 Answers2

0

Please use separate thread like AsyncTask for network operations. You are using getMethod in OnCreate() which results in exception.

  • granted, they should do the work on a different thread rather than UI thread, but not using an async task, especially if they want to update UI. To update the textview or any UI for that matter you need to hold a reference to a valid context. But consider now that a configuration change occurs, no valid context for you anymore and that's how you have a leak. If you try with async task to fire a network request and while that is in progress you decide to rotate your screen (i.e. configuration change), that network request will say goodbye. – Alex Goja Nov 04 '15 at 18:00
  • You can update UI component in AsyncTask by doing so in onPostExexcute() or onProgressUpdate() which are executed on UI thread in AsyncTask.So it is not a problem to use AsyncTask. Coming to configuration change , give me some time I'll get back to you. – SriMaharshi Manchem Nov 05 '15 at 01:12
  • http://stackoverflow.com/q/7128670/4476794 please use the method mentioned in the post for configuration change. – SriMaharshi Manchem Nov 05 '15 at 01:25
0

In your server result you are getting json array but when you are parsing as json object it

JSONObject json=new JSONObject(result);

here your result is a string type json array so you use below code to parse

JSONObject json= new JSONArray(result).get(0);

And last and important you should use AsynkTask for calling web service or long operation otherwise it will block your UI thread.

vishal jangid
  • 2,967
  • 16
  • 22