user1478434 user1478434 - 2 months ago 13
JSON Question

need help android Json Currency Converter

I have a project that ask me to build a currency converter, i already search google and got some source that can give me a reference
but i got stuck when i click calculate it doesnt change the textview to the rate of the currency..

I using a json and this is the site

http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20%28%22USDSGD%22%29&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=


this is some of the code

calculate.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
TextView texts = (TextView) findViewById(R.id.textView3);

try {
s = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22"+val[from]+val[to]+"%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=");
JSONObject jObj;
jObj = new JSONObject(s);
String theResult = jObj.getJSONObject("query").getJSONObject("results").getJSONObject("rate").getString("Rate");

texts.setText(theResult);
}

catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}


the val[from]+val[to] is come from my spinner, i have 2 spinner

the getJson code

public String getJson(String url)throws ClientProtocolException, IOException {
StringBuilder build = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String con;
while ((con = reader.readLine()) != null) {
build.append(con);
}
return build.toString();
}


please help me.. where is the wrong of this code i already try to edit and got nothing .. still when i click the button it dont give me the value to textview

Answer

i tried an activity that converts the data and displays it in a textview

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

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

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class CurrencyActivity extends Activity {

    private TextView texts;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.test);

        Button button = (Button) findViewById(R.id.calculateCmd);
        button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                new DownloadData().execute();
            }
        });

        texts = (TextView) findViewById(R.id.txtCurrency);

    }

    public String getJson(String url) throws ClientProtocolException,
            IOException {
        StringBuilder build = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        HttpResponse response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();
        InputStream content = entity.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                content));
        String con;
        while ((con = reader.readLine()) != null) {
            build.append(con);
        }
        return build.toString();
    }

    class DownloadData extends AsyncTask<Void, Integer, String> {

        ProgressDialog pd = null;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pd = new ProgressDialog(CurrencyActivity.this);
            pd.setTitle("Converting...");
            pd.setMessage("Please wait...");
            pd.setCancelable(false);
            pd.show();

        }

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

            String s;
            String theResult = "";
            try {
                s = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22USDSGD%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=");
                JSONObject jObj;
                jObj = new JSONObject(s);
                theResult = jObj.getJSONObject("query")
                        .getJSONObject("results").getJSONObject("rate")
                        .getString("Rate");

                System.out.println(theResult);
            }

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

            return theResult;
        }

        @Override
        protected void onPostExecute(String theResult) {
            super.onPostExecute(theResult);
            pd.dismiss();

            System.out.println("theResult:" + theResult);
            texts.setText(theResult);
        }
    }

}

the layout xml file i have used

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:orientation="vertical" 
        android:gravity="center"
        >

        <Button
            android:id="@+id/calculateCmd"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Calculate" />

        <TextView
            android:id="@+id/txtCurrency"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Income" >
        </TextView>
    </LinearLayout>

</RelativeLayout>

replace the URL with the values from your spinners and use the DownloadData AsyncTask in your case