Home > Mobile >  how show response of text view after clicking a button
how show response of text view after clicking a button

Time:05-13

I am trying to show response on screen using text view after clicking a button but getting error saying com.android.volley.toolbox.JsonObjectRequest cannot be cast to java.lang.CharSequence

package com.example.volleydemo;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;
import org.json.JSONObject;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    Button Click;
    TextView response;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Click = findViewById(R.id.button);
        response=findViewById(R.id.textView);
        Click.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                RequestQueue requestQueue;
                requestQueue = Volley.newRequestQueue(getApplicationContext());
                JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
                        "https://jsonplaceholder.typicode.com/todos/1",
                        null, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            Log.d("myapp", "the response is"   response.getString("title"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void one rrorResponse(VolleyError error) {
                        Log.d("myapp", "something went wrong");
                    }
                });
                requestQueue.add(jsonObjectRequest);
                response.setText((CharSequence) jsonObjectRequest);

            }
        });
    }
}

XML code here

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@ id/Click"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@ id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@ id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="36sp"
        app:layout_constraintBottom_toTopOf="@ id/button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.693" />

</androidx.constraintlayout.widget.ConstraintLayout>

errors on logcat shows i am getting this because at line 55 we can't use char sequence.so how do we get the response to textview

05/12 18:17:11: Launching 'app' on Pixel 2 API 30.
Install successfully finished in 40 s 997 ms.
$ adb shell am start -n "com.example.volleydemo/com.example.volleydemo.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 3719 on device 'Pixel_2_API_30 [emulator-5554]'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/libEGL: loaded /vendor/lib/egl/libEGL_emulation.so
D/libEGL: loaded /vendor/lib/egl/libGLESv1_CM_emulation.so
D/libEGL: loaded /vendor/lib/egl/libGLESv2_emulation.so
W/mple.volleydem: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed)
W/mple.volleydem: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
D/HostConnection: HostConnection::get() New Host Connection established 0xef161170, tid 3750
D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV_Cache ANDROID_EMU_vulkan_ignored_handles ANDROID_EMU_has_shared_slots_host_memory_allocator ANDROID_EMU_vulkan_free_memory_sync ANDROID_EMU_vulkan_shader_float16_int8 ANDROID_EMU_vulkan_async_queue_submit ANDROID_EMU_sync_buffer_data ANDROID_EMU_read_color_buffer_dma GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing ANDROID_EMU_gles_max_version_2 
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
D/EGL_emulation: eglCreateContext: 0xef160a70: maj 2 min 0 rcv 2
D/EGL_emulation: eglMakeCurrent: 0xef160a70: ver 2 0 (tinfo 0xef4ae4d0) (first time)
I/Gralloc4: mapper 4.x is not supported
D/HostConnection: createUnique: call
D/HostConnection: HostConnection::get() New Host Connection established 0xef160df0, tid 3750
D/goldfish-address-space: allocate: Ask for block of size 0x100
D/goldfish-address-space: allocate: ioctl allocate returned offset 0x3f7ffe000 size 0x2000
D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV_Cache ANDROID_EMU_vulkan_ignored_handles ANDROID_EMU_has_shared_slots_host_memory_allocator ANDROID_EMU_vulkan_free_memory_sync ANDROID_EMU_vulkan_shader_float16_int8 ANDROID_EMU_vulkan_async_queue_submit ANDROID_EMU_sync_buffer_data ANDROID_EMU_read_color_buffer_dma GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing ANDROID_EMU_gles_max_version_2 
I/OpenGLRenderer: Davey! duration=737ms; Flags=1, IntendedVsync=171246704466, Vsync=171246704466, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=171257497300, AnimationStart=171257574100, PerformTraversalsStart=171257666800, DrawStart=171711031000, SyncQueued=171752250500, SyncStart=171807610900, IssueDrawCommandsStart=171807860300, SwapBuffers=172005072600, FrameCompleted=172039808600, DequeueBufferDuration=820900, QueueBufferDuration=2784500, GpuCompleted=0, 
I/Choreographer: Skipped 53 frames!  The application may be doing too much work on its main thread.
I/OpenGLRenderer: Davey! duration=946ms; Flags=0, IntendedVsync=171263365284, Vsync=172146698582, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=172161042800, AnimationStart=172161115500, PerformTraversalsStart=172161649900, DrawStart=172174352400, SyncQueued=172175428100, SyncStart=172178406700, IssueDrawCommandsStart=172178473600, SwapBuffers=172180510600, FrameCompleted=172213004400, DequeueBufferDuration=780600, QueueBufferDuration=14149300, GpuCompleted=0, 
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.volleydemo, PID: 3719
    java.lang.ClassCastException: com.android.volley.toolbox.JsonObjectRequest cannot be cast to java.lang.CharSequence
        at com.example.volleydemo.MainActivity$1.onClick(MainActivity.java:55)
        at android.view.View.performClick(View.java:7448)
        at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1131)
        at android.view.View.performClickInternal(View.java:7425)
        at android.view.View.access$3600(View.java:810)
        at android.view.View$PerformClick.run(View.java:28305)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
I/Process: Sending signal. PID: 3719 SIG: 9

CodePudding user response:

Try this -

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "MainActivity";
    Button Click;
    TextView responseText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Click = findViewById(R.id.button);
        Click.setOnClickListener(this);
        responseText = findViewById(R.id.textView);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.button) {
            RequestQueue requestQueue;
            requestQueue = Volley.newRequestQueue(this);
            @SuppressLint("SetTextI18n") JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
                    "https://jsonplaceholder.typicode.com/todos/1",
                    null, response -> {
                try {
                    responseText.setVisibility(View.VISIBLE);
                    Log.d(TAG, "the response is"   response.getString("title"));
                    responseText.setText(" ID"   response.getString("id")   "\n Title-"  
                            response.getString("title")   "\n Completed-"  
                            response.getString("completed")   "\n User ID"
                              response.getString("userId")   "\n");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }, error -> Log.d("myapp", "something went wrong"));
            requestQueue.add(jsonObjectRequest);
        }
    }
}

CodePudding user response:

Remove this line response.setText((CharSequence) jsonObjectRequest); and

add this below line in onResponse() callback method.

response.setText(result.toString());

Something like this

@Override
public void onResponse(JSONObject result) {
 try {
         Log.d("myapp", "the response is"   response.getString("title"));
         response.setText(result.toString());     
     } catch (JSONException e) {
         e.printStackTrace();
     }
}
  • Related