JsonParsing时活动崩溃

时间:2013-04-12 10:40:14

标签: android android-asynctask currency

我正在尝试在单位转换器上制作应用程序。 我已经完成的所有其他实现,但我无法获取货币的实时值。 我发现了一种“JSON解析”方式。我搜索了它并创建了这段代码。

package com.example.unitconverter;

import java.io.IOException;

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.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class HttpExample extends Activity{

Spinner S1,S2;
TextView tv;
EditText et;
Button abutton;
HttpClient client;
JSONObject json;

static final String URL = "http://rate-exchange.appspot.com/currency?from=";

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.currency);

    S1=(Spinner)findViewById(R.id.spinner1);
    S2=(Spinner)findViewById(R.id.spinner2);
    et=(EditText)findViewById(R.id.editText1);
    tv = (TextView) findViewById (R.id.textView1);
    abutton=(Button)findViewById(R.id.button1);
    client = new DefaultHttpClient();

    abutton.setOnClickListener(new View.OnClickListener() {

        public void onClick(View arg0) {
            // TODO Auto-generated method stub

            new Read().execute("rate");

        }
    });


}

public JSONObject retrieve(String from,String to) throws ClientProtocolException,IOException,JSONException{

    StringBuilder url = new StringBuilder(URL);
    url.append(from + "&to=" + to);

    HttpGet get = new HttpGet(url.toString());
    HttpResponse r = client.execute(get);

    int status = r.getStatusLine().getStatusCode();
    if(status == 200){
        HttpEntity e = r.getEntity();
        String data = EntityUtils.toString(e);
        JSONArray timeline = new JSONArray(data);
        JSONObject last = timeline.getJSONObject(0);

        return last;

    }
    else{
        Toast.makeText(HttpExample.this, "error",Toast.LENGTH_SHORT).show();
        return null;

    }

}
public class Read extends AsyncTask<String,Integer,String>{

     @Override
        protected void onPreExecute() {
            Log.i("AsyncTask", "onPreExecute");
        }

    @Override
    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub

        try {


            json = retrieve(S1.getSelectedItem().toString(),S2.getSelectedItem().toString());

            return json.getString(params[0]);
        } 
        catch (Exception e) {
            // TODO Auto-generated catch block
            Toast.makeText(HttpExample.this, "Exception", Toast.LENGTH_LONG).show();
            e.printStackTrace();
            return null;
        }

    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        Double F=Double.parseDouble(result);
        Double D = Double.parseDouble(et.getText().toString());
        String newstring = Double.toString(D*F);

        tv.setText(newstring);

    }
}

}

xml文件包含2个包含货币缩写的Spinners,1个EditText,1个TextView和1个“转换”按钮。 当我点击“转换”时,我收到一条消息“不幸的是,UnitConverter停止工作”。

我是android新手,因此对错误知之甚少,但我从LogCat可以理解的是,doInBackground()函数存在一些问题。

请提供帮助,因为我提交此应用程序的最后日期非常接近。

提前感谢。

更新:

04-12 16:26:36.494: E/AndroidRuntime(1853): FATAL EXCEPTION: main
04-12 16:26:36.494: E/AndroidRuntime(1853): java.lang.NullPointerException
04-12 16:26:36.494: E/AndroidRuntime(1853):     at     java.lang.StringToReal.parseDouble(StringToReal.java:244)
04-12 16:26:36.494: E/AndroidRuntime(1853):     at     java.lang.Double.parseDouble(Double.java:295)
04-12 16:26:36.494: E/AndroidRuntime(1853):     at com.example.unitconverter.HttpExample$Read.onPostExecute(HttpExample.java:119)
04-12 16:26:36.494: E/AndroidRuntime(1853):     at com.example.unitconverter.HttpExample$Read.onPostExecute(HttpExample.java:1)
04-12 16:26:36.494: E/AndroidRuntime(1853):     at android.os.AsyncTask.finish(AsyncTask.java:631)
04-12 16:26:36.494: E/AndroidRuntime(1853):     at android.os.AsyncTask.access$600(AsyncTask.java:177)
04-12 16:26:36.494: E/AndroidRuntime(1853):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
04-12 16:26:36.494: E/AndroidRuntime(1853):     at android.os.Handler.dispatchMessage(Handler.java:99)
04-12 16:26:36.494: E/AndroidRuntime(1853):     at android.os.Looper.loop(Looper.java:137)
04-12 16:26:36.494: E/AndroidRuntime(1853):     at android.app.ActivityThread.main(ActivityThread.java:5041)
04-12 16:26:36.494: E/AndroidRuntime(1853):     at java.lang.reflect.Method.invokeNative(Native Method)
04-12 16:26:36.494: E/AndroidRuntime(1853):     at java.lang.reflect.Method.invoke(Method.java:511)
04-12 16:26:36.494: E/AndroidRuntime(1853):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
04-12 16:26:36.494: E/AndroidRuntime(1853):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
04-12 16:26:36.494: E/AndroidRuntime(1853):     at dalvik.system.NativeStart.main(Native Method)

更新:

我收到了错误。我使用的是JSONArray而不是JSONObject。

public JSONObject retrieve(String from,String to) throws    ClientProtocolException,IOException,JSONException{

    StringBuilder url = new StringBuilder(URL);
    url.append(from + "&to=" + to);

    HttpGet get = new HttpGet(url.toString());
    HttpResponse r = client.execute(get);

    int status = r.getStatusLine().getStatusCode();
    if(status == 200){
        HttpEntity e = r.getEntity();
        String data = EntityUtils.toString(e);
        JSONObject last = new JSONObject(data);     
        return last;

    }
    else{
        Toast.makeText(Currency.this, "Error!!!",Toast.LENGTH_SHORT).show();
        return null;

    }

谢谢大家

1 个答案:

答案 0 :(得分:3)

删除此

 Toast.makeText(HttpExample.this, "Exception", Toast.LENGTH_LONG).show();

doInBackgrond内。

由于doInBackground未在UI线程中运行,因此不允许在那里执行UI操作。

所以将toast放在onPostExecute或runonUiThred