2012-08-11 3 views
1

내 PC에서 안드로이드로 코드를 움직이는 데 좋은 행운이 아닙니다. 내 PC에서는 작동하지만 Android 폰에서는 작동하지 않는 코드에 문제가 있습니다. 나는 동일한 라이브러리 (GSON)를 사용하고 있으며, 안드로이드 장치에서 문제가되어야한다. 누군가 나를 도울 수 있습니까?코드는 PC에서는 작동하지만 Android (Gson)에서는 작동하지 않습니다.

로그 캣 :

08-10 22:39:22.400: E/AndroidRuntime(29153): FATAL EXCEPTION: AsyncTask #1 
08-10 22:39:22.400: E/AndroidRuntime(29153): java.lang.RuntimeException: An error occured while executing doInBackground() 
08-10 22:39:22.400: E/AndroidRuntime(29153): at android.os.AsyncTask$3.done(AsyncTask.java:278) 
08-10 22:39:22.400: E/AndroidRuntime(29153): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273) 
08-10 22:39:22.400: E/AndroidRuntime(29153): at java.util.concurrent.FutureTask.setException(FutureTask.java:124) 
08-10 22:39:22.400: E/AndroidRuntime(29153): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307) 
08-10 22:39:22.400: E/AndroidRuntime(29153): at java.util.concurrent.FutureTask.run(FutureTask.java:137) 
08-10 22:39:22.400: E/AndroidRuntime(29153): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208) 
08-10 22:39:22.400: E/AndroidRuntime(29153): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076) 
08-10 22:39:22.400: E/AndroidRuntime(29153): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569) 
08-10 22:39:22.400: E/AndroidRuntime(29153): at java.lang.Thread.run(Thread.java:856) 
08-10 22:39:22.400: E/AndroidRuntime(29153): Caused by: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 2 
08-10 22:39:22.400: E/AndroidRuntime(29153): at com.google.gson.Gson.fromJson(Gson.java:806) 
08-10 22:39:22.400: E/AndroidRuntime(29153): at com.google.gson.Gson.fromJson(Gson.java:761) 
08-10 22:39:22.400: E/AndroidRuntime(29153): at com.google.gson.Gson.fromJson(Gson.java:710) 
08-10 22:39:22.400: E/AndroidRuntime(29153): at com.g4apps.json.android.verification.client.JsonVerificationClass.jsonVerificationCall(JsonVerificationClass.java:73) 
08-10 22:39:22.400: E/AndroidRuntime(29153): at com.g4apps.json.android.verification.client.MainActivity$SmpProcessor.doInBackground(MainActivity.java:45) 
08-10 22:39:22.400: E/AndroidRuntime(29153): at com.g4apps.json.android.verification.client.MainActivity$SmpProcessor.doInBackground(MainActivity.java:1) 
08-10 22:39:22.400: E/AndroidRuntime(29153): at android.os.AsyncTask$2.call(AsyncTask.java:264) 
08-10 22:39:22.400: E/AndroidRuntime(29153): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305) 
08-10 22:39:22.400: E/AndroidRuntime(29153): ... 5 more 
08-10 22:39:22.400: E/AndroidRuntime(29153): Caused by: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 2 
08-10 22:39:22.400: E/AndroidRuntime(29153): at com.google.gson.stream.JsonReader.nextString(JsonReader.java:464) 
08-10 22:39:22.400: E/AndroidRuntime(29153): at com.google.gson.internal.bind.TypeAdapters$13.read(TypeAdapters.java:349) 
08-10 22:39:22.400: E/AndroidRuntime(29153): at com.google.gson.internal.bind.TypeAdapters$13.read(TypeAdapters.java:337) 
08-10 22:39:22.400: E/AndroidRuntime(29153): at com.google.gson.Gson.fromJson(Gson.java:795) 
08-10 22:39:22.400: E/AndroidRuntime(29153): ... 12 more 

내 클래스 :

package com.g4apps.json.android.verification.client; 

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.io.UnsupportedEncodingException; 
import java.net.URI; 
import java.util.ArrayList; 
import java.util.List; 
import org.apache.http.HttpResponse; 
import org.apache.http.NameValuePair; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.message.BasicNameValuePair; 

import com.google.gson.*; 
import com.google.gson.reflect.TypeToken; 



// The Return class defines the structure of the json object returned by the web service 
public class JsonVerificationClass { 

    public static class VerificationData { 
     private String Name; 
     private String Phone; 

     public VerificationData (String name, String smartphone){ 
      this.Name=name; 
      this.Phone=smartphone; 
     } 

     public String getName() { return Name; } 

     public String getSmartPhone() { return Phone; } 
    } 

    // jsonCall is the actual call to the webservice 
    public static String jsonVerificationCall(URI url, String app, VerificationData data) { 


     try { 
      //We need to json objects. One for the request and one for the response 
      //The request object is simple and doesn't require an object class to define it. 
      Gson json = new Gson(); 
      String jsondata= json.toJson(data); 

      // We use the same HttpClient and HttpPost commands in both the PC and Android versions. 
      // These libraries are included in the Android SDK but must be added for the PC. 
      HttpClient client = new DefaultHttpClient(); 
      HttpPost post2 = new HttpPost(url); 

      // We use list to List to make the Post Entities 
      List<NameValuePair> namevaluePairs = new ArrayList<NameValuePair>(1); 
      namevaluePairs.add(new BasicNameValuePair("app",app)); 
      namevaluePairs.add(new BasicNameValuePair("data",jsondata.toString())); 
      //System.out.println(namevaluePairs.toString()); 
      post2.setEntity(new UrlEncodedFormEntity(namevaluePairs)); 
      HttpResponse response = client.execute(post2); 

      //Read in the response and rebuild the json string 
      BufferedReader rd= new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 
      StringBuilder myresponse = new StringBuilder(); 
      String inputline; 
      while((inputline = rd.readLine()) !=null) myresponse.append(inputline); 

      //Get the type from Return Object so we can remove it from the Json String 
      java.lang.reflect.Type StringType = new TypeToken<String>(){}.getType(); 
      rd.close(); 
      //System.out.println(myresponse.toString()); 
      String return2= new Gson().fromJson(myresponse.toString(), StringType); 
      return return2; 
     } 
     catch (UnsupportedEncodingException uee) { 
      uee.printStackTrace(); 
     } 
     catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     return null; 
    } 

} 

내 활동 :

package com.g4apps.json.android.verification.client; 

import java.net.URI; 
import java.net.URISyntaxException; 

import com.g4apps.json.android.verification.client.JsonVerificationClass; 
import com.g4apps.json.android.verification.client.JsonVerificationClass.VerificationData; 

import android.os.AsyncTask; 
import android.os.Bundle; 
import android.app.Activity; 
import android.view.Menu; 
import android.widget.TextView; 


public class MainActivity extends Activity { 
    private TextView tv; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     tv = (TextView)findViewById(R.id.TextView01); 


     //Start new task and run SmpProcessor (Android 2.3+ prohibits Networking activities from running in main thread. 
     SmpProcessor task = new SmpProcessor(); 
     task.execute(); 

    } 
    // added asynctask though other thread methods can be used 
    private class SmpProcessor extends AsyncTask <Void,Void,String> { 

      // doInBackground sets up variables and calls jsonCall. multiple to jsoncall can be made from the same thread. 
      @Override 
      protected String doInBackground(Void... voids){ //String[] doInBackground(Void... voids){ 

       try { 

        URI url = new URI("http://myservice.com/webservices.php"); 
        String app="verify"; 
        VerificationData data = new VerificationData("Sam","9055551212"); 

        // Make jsonCall with will return Return Object 
        String result = JsonVerificationClass.jsonVerificationCall(url,app,data); 


        return result; 
       } catch (URISyntaxException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 
       //return null; 
       return null; 
      } 
      // Handled the retrieval of the data in onPostExecute so I could output it to the android device through the MainActivity. 
      protected void onPostExecute(String result) { 


       tv.setText("Response: " + result); 


       // Handle or call processing for data here as it needs to be done post html call. 
      } 
     } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     getMenuInflater().inflate(R.menu.activity_main, menu); 
     return true; 
    } 


} 
+1

또한이 오류를 생성하는 가장 작은 json 파일을 게시하십시오. –

+0

그 오류를 발견 한 아. 서버가 오류 응답을 위해 다른 형식을 반환 중입니다. 메시지를 생성하는 코드가 정확해야하지만 오류 응답을받는 이유를 잘 모릅니다. – Codeguy007

답변

1

죄송합니다 제가 잘못 서비스를 호출하고이 오류 메시지를 반환 한 것 같아요 클라이언트가 예상했던 것과 다른 형식.

이 은 { "문자열을"} 기대하고했습니다

{ "상태": "문자열", "데이터": "문자열 []"}는 JSON 문자열을보고 제안의 더크에

감사 계시 대답.

+0

이므로 답을 해결 대답으로 표시 할 수 있습니다. 만약 당신이 질문을 미해결 질문에있을 것 입니다이 사촌. – Hosein

+0

당신은 내 자신의 대답을 바르게 받아 들일 수 없다는 것을 알고 있습니다. – Codeguy007

+0

난 할 수있어. 이를위한 옵션이 있습니다. – Hosein

관련 문제