Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
345 views
in Technique[技术] by (71.8m points)

java - TextView isn't updated with JSON Response

I have 3 textviews I'm attempting to update (nameTv, contentTv, publishedTv) with data obtained from a JSON response. When I execute the code shown below the textviews do not update - and when I set a breakpoint at TextView nameTv = (TextView) findViewById(R.id.name); it never seems to reach it and I'm unsure why.

JAVA

public class Player extends YouTubeBaseActivity implements
YouTubePlayer.OnInitializedListener {

    public static final String API_KEY = "XXXXXXXXXXXXXXXXXXXXXXXXXXX";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.player);
        String title = getIntent().getStringExtra("title");
        String uploader = getIntent().getStringExtra("uploader");
        String viewCount = getIntent().getStringExtra("viewCount");
        TextView titleTv = (TextView) findViewById(R.id.titleTv);
        TextView uploaderTv = (TextView) findViewById(R.id.uploaderTv);
        TextView viewCountTv = (TextView) findViewById(R.id.viewCountTv);

        titleTv.setText(title);
        uploaderTv.setText("by" + uploader + " |");
        viewCountTv.setText(viewCount + " views");
        YouTubePlayerView youTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtubeplayerview);
        youTubePlayerView.initialize(API_KEY, this);
        GetYouTubeUserCommentsTask task = new GetYouTubeUserCommentsTask(null,
                viewCount);
        task.execute();
    }

    @Override
    public void onInitializationFailure(Provider provider,
            YouTubeInitializationResult result) {
        Toast.makeText(getApplicationContext(), "onInitializationFailure()",
                Toast.LENGTH_LONG).show();
    }

    @Override
    public void onInitializationSuccess(Provider provider,
            YouTubePlayer player, boolean wasRestored) {
        if (!wasRestored) {
            String video_id = getIntent().getStringExtra("id");
            player.loadVideo(video_id);
        }
    }

    public final class GetYouTubeUserCommentsTask extends
    AsyncTask<Void, Void, Void> {

        public static final String LIBRARY = "CommentsLibrary";
        private final Handler replyTo;
        private final String username;
        String video_id = getIntent().getStringExtra("id");

        public GetYouTubeUserCommentsTask(Handler replyTo, String username) {
            this.replyTo = replyTo;
            this.username = username;
        }


        @Override
        protected Void doInBackground(Void... arg0) {
            try {

                HttpClient client = new DefaultHttpClient();

                HttpUriRequest request = new HttpGet(
                        "http://gdata.youtube.com/feeds/api/videos/"
                                + video_id
                                + "/comments?v=2&alt=json&start-index=1&max-results=50&prettyprint=true");

                HttpResponse response = client.execute(request);

                String jsonString = StreamUtils.convertToString(response
                        .getEntity().getContent());

                JSONObject json = new JSONObject(jsonString);
                JSONArray jsonArray = json.getJSONObject("feed").getJSONArray(
                        "entry");

                List<Comments> comments = new ArrayList<Comments>();

                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);

                    String name = jsonObject.optString("name","defaultValue");
                    String content = jsonObject.optString("content","defaultValue");
                    String published = jsonObject.optString("published","defaultValue");

                    comments.add(new Comments(name, content, published));
                }

                CommentsLibrary lib = new CommentsLibrary(jsonString, jsonString, jsonString);

                Bundle data = new Bundle();
                data.putSerializable(LIBRARY, lib);

                Message msg = Message.obtain();
                msg.setData(data);
                replyTo.sendMessage(msg);

            } catch (ClientProtocolException e) {
                Log.e("Feck", e);
            } catch (IOException e) {
                Log.e("Feck", e);
            } catch (JSONException e) {
                Log.e("Feck", e);
            }
            return null;
        }


        @Override
        protected void onPostExecute(Void result) {
            TextView nameTv = (TextView) findViewById(R.id.name);   
            nameTv.setText(com.idg.omv.domain.CommentsLibrary.getName());

            TextView contentTv = (TextView) findViewById(R.id.content); 
            contentTv.setText(com.idg.omv.domain.CommentsLibrary.getContent());

            TextView publishedTv = (TextView) findViewById(R.id.published); 
            publishedTv.setText(com.idg.omv.domain.CommentsLibrary.getPublished());
        }
    }
}

CommentsLibrary.java

public class CommentsLibrary implements Serializable{
    // The username of the owner of the comment
    private static String name;
    // The  comment
        private static String content;
    // The date the comment was published
    private static String published;

    public CommentsLibrary(String name, String content, String published) {
        this.name = name;
        this.content = content;
        this.published = published;
    }

    /**
     * @return the user name
     */
    public static String getName() {
        return name;
    }

    /**
     * @return the videos
     */
    public static String getContent() {
        return content;
    }

    /**
     * @return the videos
     */
    public static String getPublished() {
        return published;
    }
}

LOGCAT:

12-11 14:23:14.301: E/AndroidRuntime(2654): FATAL EXCEPTION: AsyncTask #2
12-11 14:23:14.301: E/AndroidRuntime(2654): java.lang.RuntimeException: An error occured while executing doInBackground()
12-11 14:23:14.301: E/AndroidRuntime(2654):     at android.os.AsyncTask$3.done(AsyncTask.java:299)
12-11 14:23:14.301: E/AndroidRuntime(2654):     at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
12-11 14:23:14.301: E/AndroidRuntime(2654):     at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
12-11 14:23:14.301: E/AndroidRuntime(2654):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
12-11 14:23:14.301: E/AndroidRuntime(2654):     at java.util.concurrent.FutureTask.run(FutureTask.java:137)
12-11 14:23:14.301: E/AndroidRuntime(2654):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
12-11 14:23:14.301: E/AndroidRuntime(2654):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
12-11 14:23:14.301: E/AndroidRuntime(2654):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
12-11 14:23:14.301: E/AndroidRuntime(2654):     at java.lang.Thread.run(Thread.java:856)
12-11 14:23:14.301: E/AndroidRuntime(2654): Caused by: java.lang.NullPointerException
12-11 14:23:14.301: E/AndroidRuntime(2654):     at com.idg.omv.ui.phone.Player$GetYouTubeUserCommentsTask.doInBackground(Player.java:134)
12-11 14:23:14.301: E/AndroidRuntime(2654):     at com.idg.omv.ui.phone.Player$GetYouTubeUserCommentsTask.doInBackground(Player.java:1)
12-11 14:23:14.301: E/AndroidRuntime(2654):     at android.os.AsyncTask$2.call(AsyncTask.java:287)
12-11 14:23:14.301: E/AndroidRuntime(2654):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
12-11 14:23:14.301: E/AndroidRuntime(2654):     ... 5 more
12-11 14:23:23.981: I/Choreographer(2654): Skipped 576 frames!  The application may be doing too much work on its main thread.
12-11 14:23:24.621: E/ActivityThread(2654): Activity com.idg.omv.ui.phone.Player has leaked ServiceConnection com.google.android.youtube.player.internal.r$e@41b1e948 that was originally bound here
12-11 14:23:24.621: E/ActivityThread(2654): android.app.ServiceConnectionLeaked: Activity com.idg.omv.ui.phone.Player has leaked ServiceConnection com.google.android.youtube.player.internal.r$e@41b1e948 that was originally bound here
12-11 14:23:24.621: E/ActivityThread(2654):     at android.app.LoadedApk$ServiceDispatcher.<init>(LoadedApk.java:966)
12-11 14:23:24.621: E/ActivityThread(2654):     at android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:860)
12-11 14:23:24.621: E/ActivityThread(2654):     at android.app.ContextImpl.bindService(ContextImpl.java:1364)
12-11 14:23:24.621: E/ActivityThread(2654):     at android.app.ContextImpl.bindService(ContextImpl.java:1356)
12-11 14:23:24.621: E/ActivityThread(2654):     at android.content.ContextWrapper.bindService(ContextWrapper.java:401)
12-11 14:23:24.621: E/ActivityThread(2654):     at com.google.android.youtube.player.internal.r.e(Unknown Source)
12-11 14:23:24.621: E/ActivityThread(2654):     at com.google.android.youtube.player.YouTubePlayerView.a(Unknown Source)
12-11 14:23:24.621: E/ActivityThread(2654):     at com.google.android.youtube.player.YouTubeBaseActivity$a.a(Unknown Source)
12-11 14:23:24.621: E/ActivityThread(2654):     at com.google.android.youtube.player.YouTubePlayerView.initialize(Unknown Source)
12-11 14:23:24.621: E/ActivityThread(2654):     at com.idg.omv.ui.phone.Player.onCreate(Player.java:57)
12-11 14:23:24.621: E/ActivityThread(2654):     at android.app.Activity.performCreate(Activity.java:5206)
12-11 14:23:24.621: E/ActivityThread(2654):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
12-11 14:23:24.621: E/ActivityThread(2654):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2074)
12-11 14:23:24.621: E/ActivityThread(2654):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2135)
12-11 14:23:24.621: E/ActivityThread(2654):     at android.app.ActivityThread.access$700(ActivityThread.java:140)
12-11 14:23:24.621: E/ActivityThread(2654):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1237)
12-11 14:23:24.621: E/ActivityThread(2654):     at android.os.Handler.dispatchMessage(Handler.java:99)
12-11 14:23:24.621: E/ActivityThread(2654):     at android.os.Looper.loop(Looper.java:137)
12-11 14:23:24.621: E/ActivityThread(2654):     at android.app.ActivityThread.main(ActivityThread.java:4921)
12-11 14:23:24.621: E/ActivityThread(2654):     at java.lang.reflect.Method.invokeNative(Native Method)
12-11 14:23:24.621: E/ActivityThread(2654):     at java.lang.reflect.Method.invoke(Method.java:511)
12-11 14:23:24.621: E/ActivityThread(2654):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
12-11 14:23:24.621: E/ActivityThread(2654):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
12-11 14:23:24.621: E/ActivityThread(2654):     at dalvik.system.NativeStart.main(Native Method)
12-11 14:23:24.876: D/dalvikvm(2654): GC_CONCURRENT freed 1495K, 18% free 25511K/30983K, paused 12ms+3ms, total 48ms
12-11 14:23:24.876: D/dalvikvm(2654): WAIT_FOR_CONCURRENT_GC blocked 18ms

EDIT: In Response to @Raghunandan

If I understand you correctly I need to pass the handler replyTo:

GetYouTubeUserCommentsTask task = new GetYouTubeUserCommentsTask(Handler replyTo, String username);

Then:

public GetYouTubeUserCommentsTask(Handler replyTo, String username) {
        this.replyTo = replyTo; // replyTo is null
        this.username = username;
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
GetYouTubeUserCommentsTask task = new GetYouTubeUserCommentsTask(null,
                viewCount); // passing null. 

And you have

public GetYouTubeUserCommentsTask(Handler replyTo, String username) {
        this.replyTo = replyTo; // replyTo is null
        this.username = username;
    }

replyTo is null. You need to Initialize the handler replyTo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...