2013-04-12 2 views
0

단위 변환기에서 앱을 만들려고합니다. 내가 수행 한 다른 모든 구현은하지만 통화에 대한 실시간 값을 가져올 수 없습니다. "JSON 구문 분석"방식을 발견했습니다. 나는 그것을 찾아서이 코드를 만들었다.JsonParsing 동안 활동이 중단됩니다.

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 파일은 통화 약어, 1 글고, 1 텍스트 뷰 1 개 버튼 "변환"를 포함하는 2 개 스피너가 포함되어 있습니다. "Convert"를 클릭하면 "Unconunately, UnitConverter working stopped"이라는 메시지가 나타납니다.

나는 android에 익숙하지 않기 때문에 오류에 대해 많이 알지 못하지만 LogCat에서 이해할 수있는 것은 doInBackground() 함수에 문제가 있다는 것입니다.

이 응용 프로그램의 제출에 대한 나의 마지막 날짜가 가까와서 도와주세요.

미리 감사드립니다.

UPDATE :

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) 

UPDATE :

내 error..I 대신 된 JSONObject의 JSONArray를 사용하고있어

.

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

로그 캣에 내가 대답 – jimpanzer

+0

을 토스트를 배치 토스트, 오류가 동일합니다 –

답변

3

doInBackgrond의 안쪽이

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

를 제거합니다.

doInBackground은 UI 스레드에서 실행되지 않으므로 UI ​​작업을 수행 할 수 없습니다.

그래서 심지어 제거한 후 ... 제발, onPostExecute 또는 runonUiThred

+0

예, 당신이 수행 할 수 없습니다 UI 작업을 추가 한 jimpanzer- @ – Sunny

+0

의 로그 캣에게 doInBackground, 하나의 –

+0

@AkshaySethi doInBackground에서'null '을 반환하고'null' 값에 연산을 수행하려고하면'NullPointerException'이 발생합니다 – Pragnani

관련 문제