2014-09-15 3 views
0

json 파일에서 json 객체를 가져와야합니다.이 파일은 url입니다.json 객체를 추출 할 때 오류가 발생했습니다.

내 코드가 doInBackground()에서 java.lang.RuntimeException을 던지고 jsonObject 변환 예외에서 문자열을 던지고 있습니다. 누구든지이 일을 도와 줄 수 있습니까? 나는 안드로이드 프로그래밍이 처음이다.

package course.examples.networkingearthquake; 


import android.support.v7.app.ActionBarActivity; 
import android.os.Bundle; 
import android.os.AsyncTask; 
import android.widget.Button; 
import android.view.View; 
import android.widget.TextView; 
import android.widget.EditText; 

import java.io.IOException; 
import java.util.ArrayList; 
import java.util.List; 


import org.apache.http.HttpResponse; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.ResponseHandler; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.impl.client.BasicResponseHandler; 
import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 
import org.json.JSONTokener; 

import android.net.http.AndroidHttpClient; 

public class HttpActivity extends ActionBarActivity { 

TextView mTextView; 
EditText etInput; 
TextView input; 
String number;//edited 
int num;//edited 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_socket); 

     mTextView = (TextView)findViewById(R.id.text1); 
     input = (TextView)findViewById(R.id.input); 
     etInput = (EditText)findViewById(R.id.etInput); 
     input.setText("Input"); 

     //number = etInput.getText().toS(); 

     final Button btDisplay = (Button)findViewById(R.id.btDisplay); 
     btDisplay.setText("DISPLAY"); 

     btDisplay.setOnClickListener(new View.OnClickListener(){ 
      public void onClick(View v) { 

       new HttpGetTask().execute(); 

       } 
     }); 
    } 


private class HttpGetTask extends AsyncTask<Void, Void, String>{ 

     private static final String TAG = "HttpGetTask"; 
     private static final String URL = "http://earthquake.usgs.gov/earthquakes/feed/geojsonp/2.5/week"; 

     AndroidHttpClient mClient = AndroidHttpClient.newInstance("");           

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

      HttpGet request = new HttpGet(URL); 
      JSONResponseHandler responseHandler = new JSONResponseHandler(); 
      // ResponseHandler<String> responseHandler = new BasicResponseHandler(); 

      try{ 

       return mClient.execute(request,responseHandler); 

      }catch(ClientProtocolException exception){ 
      exception.printStackTrace(); 
      }catch(IOException exception){ 
       exception.printStackTrace(); 
      } 
      return null; 
      } 

     @Override 
     protected void onPostExecute(String result){ 
      if(null != mClient) 
       mClient.close(); 
      mTextView.setText(result); 
     } 

    } 
private class JSONResponseHandler implements ResponseHandler<String>{ 


    @Override 
    public String handleResponse(HttpResponse response) 
    throws ClientProtocolException, IOException { 
     String result = null; 
     String JSONResponse = new BasicResponseHandler().handleResponse(response); 
     JSONResponse = JSONResponse.substring(17, JSONResponse.length()-3); 
     num = Integer.parseInt(number);// edited 
     try { 
      JSONObject responseObject = (JSONObject) new JSONTokener(
        JSONResponse).nextValue(); 
      JSONArray features = responseObject.getJSONArray("features"); 
      JSONObject retObject = (JSONObject)features.get(num);//edited 
     // JSONObject geometry = (JSONObject)retObject.get("geometry"); 

      result = retObject.toString(); 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
     return result; 
    } 
    } 
+0

무효 JSON 예외로 디버깅, 내가보기 엔 콘솔에 인쇄를 제안/문자의 문자열이 실제로 보이는 함께 작업하는 것을보고 다른 시간에 로그인합니다. 그렇게하면 모든 단계에서 유효한 JSON으로 작업하고 있는지 확인할 수 있습니다. – mmcrae

답변

1

json으로는 URL에 의해 반환 당신이 containts이 eqfeed_callback 지정()를 유효 JSON 만들기 위해 제거 될 필요가있다.

응답 처리기에서이 작업을 수행 한 것처럼 보이지만 시작과 끝 모두에서 한 문자를 너무 많이 잘라내는 것 같습니다.

이 시도 :

JSONResponse = JSONResponse.substring(16, JSONResponse.length()-2); 
+0

감사합니다. 나는 당신이 지적한 실수를하고 있었고 지금은 실행 중이다. –

+0

나는 내 코드를 편집하고 주석을 "편집"이라고 표시했다. edittext 문자열을 정수로 변환하려고하지만 NumberFormatException을 던지고 있습니다. 이걸 잘 도와 줄 수 있어요? –

+1

num = Integer.parseInt (etInput.getText(). toString()); 잘 작동해야합니다. 숫자 만 입력 하시겠습니까? – Boren

관련 문제