代码适用于PC但不适用于Android(Gson)

时间:2012-08-11 02:56:32

标签: java android android-asynctask httpclient gson

我没有好运将代码从我的PC转移到Android。我在使用可在我的电脑上运行的代码时出现问题但在我的Android手机上没有问题。我正在使用相同的库(GSON),我正在做的事情应该是Android设备的问题。有人能帮助我吗?

logcat的:

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 个答案:

答案 0 :(得分:1)

对不起,我想我拨打了错误的服务,并且它返回的错误信息格式与客户期望的格式不同。

期待{“String”}并得到{“Status”:“String”,“Data”:“String []”}

感谢德克的建议,看看json字符串显示答案。