Home > Blockchain >  extract data from JSON response volley android
extract data from JSON response volley android

Time:07-18

I´m trying to extract data from my JSON response from php in kotlin. This it´s result from my php:

Log.d(TAG, "Login Response: $response")
Login Response: {"data":{"name":"david","surname":null,"email":"[email protected]","phone":null,"password":"123456"}}

but when i access to this json:

W/System.err: org.json.JSONException: No value for name
W/System.err:     at org.json.JSONObject.get(JSONObject.java:400)
W/System.err:     at org.json.JSONObject.getString(JSONObject.java:561)
W/System.err:     at com.example.citysportgym.MainActivity.login$lambda-1(MainActivity.kt:53)

i want extract data from my json to create array or arrayList to send this array to my activity. But i don´t know how i can access to this JSON.

this function it´s to login in my app:

private fun login(email:String, password:String) {
        //creating volley string request
        val stringRequest: StringRequest = object : StringRequest(Method.POST, EndPoint.URL,
            Response.Listener { response ->
                Log.d(TAG, "Login Response: $response")
                try {
                    val jsonObject = JSONObject(response)
                    //Log.d(TAG, "JSON: $jsonObject")

                    if (jsonObject != null) {
                        val name = jsonObject.getString("name")
                        val surname = jsonObject.getString("surname")
                        val email = jsonObject.getString("email")
                        val phone = jsonObject.getInt("phone")
                        val password = jsonObject.getString("password")

                        Log.d(TAG, "JSON: $email")

                        val intent = Intent(this, ProfileActivity::class.java)
                        startActivity(intent)
                        Toast.makeText(applicationContext, "Logged ok", Toast.LENGTH_SHORT).show()
                    }
                } catch (e: JSONException) {
                    e.printStackTrace()
                }
            },
            Response.ErrorListener { println("volley Error .................") }) {
            @Throws(AuthFailureError::class)
            override fun getParams(): Map<String, String>? {
                val params: MutableMap<String, String> = HashMap()
                params["action"] = "login"
                params["email"] = email
                params["password"] = password
                return params
            }
        }

        VolleySingleton.instance?.addToRequestQueue(stringRequest)
    }

UPDATE

I solve with comment in this thread. Now i´m trying to set text from bundle

i´m doing:

private var editTextName: EditText? = null

editTextName = findViewById<EditText>(R.id.userName)

// set Strings in activity
editTextName!!.setText(name)

But android studio return a null pointer exception. I check my xml:

<EditText
            android:id="@ id/userName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:backgroundTint="#F8F6F6"
            android:ems="10"
            android:hint="Nombre"
            android:inputType="textPersonName"
            android:textColor="#F8F6F6"
            android:textColorHint="#FAFAFA" />

        <EditText
            android:id="@ id/userAddress"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:backgroundTint="#FDFCFC"
            android:ems="10"
            android:hint="Direccion"
            android:inputType="textPersonName"
            android:textColor="#F8F6F6"
            android:textColorHint="#FBFBFB" />

My error:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.citysportgym/com.example.citysportgym.ProfileActivity}: java.lang.NullPointerException

In my setText it´s my error. I don´t know that i´m doing wrong.

Update 2

in my mainActivity:

val intent = Intent(this, ProfileActivity::class.java)
                        // set parameter to activity
                        val b = Bundle()
                        b.putString("name", name)
                        b.putString("surname", surname)
                        b.putString("email", email)
                        b.putString("phone", phone)
                        b.putString("password", password)
                        intent.putExtras(b) //Put your id to your next Intent

                        startActivity(intent)
                        Toast.makeText(applicationContext, "Logged ok", Toast.LENGTH_SHORT).show()

In my ProfileActivity:

editTextName = findViewById<EditText>(R.id.userName)
        //var address = findViewById<EditText>(R.id.userName)
        editTextEmail = findViewById<EditText>(R.id.userEmailText)
        editTextphone = findViewById<EditText>(R.id.userPhone)
        editTextPassword = findViewById<EditText>(R.id.userPasswordEdit)

        val b = intent.extras
        var name = ""
        var surname = ""
        var userEmail = ""
        var phone = ""
        var password = ""

        if (b != null) {
            name = b.getString("name").toString()
            surname = b.getString("surname").toString()
            userEmail = b.getString("email").toString()
            phone = b.getString("phone").toString()
            password = b.getString("password").toString()

            Log.d(ContentValues.TAG, "JSON: ${editTextName}")

            // set Strings in activity
            /*editTextName!!.setText(name)
            //address.setText()
            editTextEmail!!.setText(userEmail)
            editTextphone!!.setText(phone)
            editTextPassword!!.setText(password)*/
        }

But i have a null pointer in editTextName = findViewById<EditText>(R.id.userName)

in my xml:

<EditText
            android:id="@ id/userName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:backgroundTint="#F8F6F6"
            android:editable="true"
            android:ems="10"
            android:hint="Nombre"
            android:inputType="textPersonName"
            android:textColor="#F8F6F6"
            android:textColorHint="#FAFAFA"
            tools:ignore="Deprecated" />

in my manifest:

<activity
            android:name=".ProfileActivity"
            android:exported="true" />

This field, in log android studio it´s null. I don´t know that i´m doing wrong. Maybe i don´t say taht my EditText it´s in fragments

UPDATE 3

MainActivity

package com.example.citysportgym

import android.content.ContentValues.TAG
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.android.volley.AuthFailureError
import com.android.volley.Response
import com.android.volley.toolbox.StringRequest
import com.example.citysportgym.EndPoint.EndPoint
import com.example.citysportgym.singleton.VolleySingleton
import org.json.JSONException
import org.json.JSONObject


class MainActivity : AppCompatActivity() {
    private var editTextEmail: EditText? = null
    private var editTextPassword: EditText? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        // get btnLogin to set action
        val btnLogin = findViewById<Button>(R.id.btnLogin)
        editTextEmail = findViewById<EditText>(R.id.userEmail)
        editTextPassword = findViewById<EditText>(R.id.userPassword)


        // ACTION BUTTON LOGIN
        btnLogin.setOnClickListener{
            login(editTextEmail!!.getText().toString(), editTextPassword!!.getText().toString())
        }
    }



    // function login
    private fun login(email:String, password:String) {
        //creating volley string request
        val stringRequest: StringRequest = object : StringRequest(Method.POST, EndPoint.URL,
            Response.Listener { response ->
                try {
                    val jsonObject = JSONObject(response)

                    if (jsonObject != null) {
                        val dataJson: JSONObject = jsonObject.getJSONObject("user")
                        val name = dataJson.getString("name")
                        val surname = dataJson.getString("surname")
                        val email = dataJson.getString("email")
                        val phone = dataJson.getString("phone")
                        val password = dataJson.getString("password")


                        val intent = Intent(this, ProfileActivity::class.java)
                        // set parameter to activity
                        val b = Bundle()
                        b.putString("name", name)
                        b.putString("surname", surname)
                        b.putString("email", email)
                        b.putString("phone", phone)
                        b.putString("password", password)
                        intent.putExtras(b) //Put your id to your next Intent

                        startActivity(intent)
                        Toast.makeText(applicationContext, "Logged ok", Toast.LENGTH_SHORT).show()
                    }
                } catch (e: JSONException) {
                    e.printStackTrace()
                }
            },
            Response.ErrorListener { println("volley Error .................") }) {
            @Throws(AuthFailureError::class)
            override fun getParams(): Map<String, String>? {
                val params: MutableMap<String, String> = HashMap()
                params["action"] = "login"
                params["email"] = email
                params["password"] = password
                return params
            }
        }

        VolleySingleton.instance?.addToRequestQueue(stringRequest)
    }
}

Profile Ativity:

package com.example.citysportgym

import android.content.ContentValues
import android.os.Bundle
import android.util.Log
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import androidx.viewpager2.widget.ViewPager2
import com.example.citysportgym.Adapter.MyAdapter
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator

class ProfileActivity : AppCompatActivity() {
    private var tabTitle = arrayOf("Perfil", "Actividades", "Membresia")
    private var editTextName: EditText? = null
    private var editTextEmail: EditText? = null
    private var editTextphone: EditText? = null
    private var editTextPassword: EditText? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_profile)
        // pager show content
        var pager = findViewById<ViewPager2>(R.id.viewPagerProfile)
        // tabLayout it´s TabsMenu
        var tabLayout = findViewById<TabLayout>(R.id.profileMenu)
        // Personaliced Adaprter
        pager.adapter = MyAdapter(supportFragmentManager, lifecycle)

        TabLayoutMediator(tabLayout, pager) { tab, position ->
            tab.text = tabTitle[position]
        }.attach()

        editTextName = findViewById<EditText>(R.id.userName)
        //var address = findViewById<EditText>(R.id.userName)
        editTextEmail = findViewById<EditText>(R.id.userEmailText)
        editTextphone = findViewById<EditText>(R.id.userPhone)
        editTextPassword = findViewById<EditText>(R.id.userPasswordEdit)

        val b = intent.extras
        var name = ""
        var surname = ""
        var userEmail = ""
        var phone = ""
        var password = ""

        if (b != null) {
            name = b.getString("name").toString()
            surname = b.getString("surname").toString()
            userEmail = b.getString("email").toString()
            phone = b.getString("phone").toString()
            password = b.getString("password").toString()

            Log.d(ContentValues.TAG, "JSON: ${editTextName}")
            Log.d(ContentValues.TAG, "JSON: ${name}")

            // set Strings in activity
            /*editTextName!!.setText(name)
            //address.setText()
            editTextEmail!!.setText(userEmail)
            editTextphone!!.setText(phone)
            editTextPassword!!.setText(password)*/
        }
    }
}

ProfileFragment

package com.example.citysportgym.Fragments

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import com.example.citysportgym.R

// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
 * A simple [Fragment] subclass.
 * Use the [ProfileFragment.newInstance] factory method to
 * create an instance of this fragment.
 */
class ProfileFragment : Fragment() {
    // TODO: Rename and change types of parameters
    private var param1: String? = null
    private var param2: String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            param1 = it.getString(ARG_PARAM1)
            param2 = it.getString(ARG_PARAM2)
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        val view: View =  inflater.inflate(R.layout.fragment_profile, container, false)
        var userName = view.findViewById<EditText>(R.id.userName)
        var userAddress = view.findViewById<EditText>(R.id.userAddress)
        var userEmailText = view.findViewById<EditText>(R.id.userEmailText)
        var userPhone = view.findViewById<EditText>(R.id.userPhone)
        var userPasswordEdit = view.findViewById<EditText>(R.id.userPasswordEdit)

        return view
    }

    companion object {
        /**
         * Use this factory method to create a new instance of
         * this fragment using the provided parameters.
         *
         * @param param1 Parameter 1.
         * @param param2 Parameter 2.
         * @return A new instance of fragment ProfileFragment.
         */
        // TODO: Rename and change types and number of parameters
        @JvmStatic
        fun newInstance(param1: String, param2: String) =
            ProfileFragment().apply {
                arguments = Bundle().apply {
                    putString(ARG_PARAM1, param1)
                    putString(ARG_PARAM2, param2)
                }
            }
    }
}

Thanks for help

Thanks for readme and sorry for my bad english

CodePudding user response:

You have missed the "data" JSONObject from your json. You have Response and data 2 JSONObjects that you need to add. Please find below code I have added one line of code and changed object parameters in your code .

 private fun login(email:String, password:String) {
        //creating volley string request
        val stringRequest: StringRequest = object : StringRequest(Method.POST, EndPoint.URL,
            Response.Listener { response ->
                Log.d(TAG, "Login Response: $response")
                try {
                    val jsonObject = JSONObject(response)
                    //Log.d(TAG, "JSON: $jsonObject")

                    if (jsonObject != null) {
                        val dataJson: JSONObject = jsonObject.getJSONObject("data")
                        val name = dataJson.getString("name")
                        val surname = dataJson.getString("surname")
                        val email = dataJson.getString("email")
                        val phone = dataJson.getInt("phone")
                        val password = dataJson.getString("password")

                        Log.d(TAG, "JSON: $email")

                        val intent = Intent(this, ProfileActivity::class.java)
                        startActivity(intent)
                        Toast.makeText(applicationContext, "Logged ok", Toast.LENGTH_SHORT).show()
                    }
                } catch (e: JSONException) {
                    e.printStackTrace()
                }
            },
            Response.ErrorListener { println("volley Error .................") }) {
            @Throws(AuthFailureError::class)
            override fun getParams(): Map<String, String>? {
                val params: MutableMap<String, String> = HashMap()
                params["action"] = "login"
                params["email"] = email
                params["password"] = password
                return params
            }
        }

        VolleySingleton.instance?.addToRequestQueue(stringRequest)}

CodePudding user response:

As per your Update

In your Success response pass values

 val intent = Intent(baseContext, ProfileActivity::class.java)
                intent.putExtra("name", name)
                intent.putExtra("surname", surname)
                intent.putExtra("email", email)
                Toast.makeText(applicationContext, "Logged ok", Toast.LENGTH_SHORT).show()
                startActivity(intent)
                  finish()

And with your ProfileActivity get values which you passed from First Activity.

 val name = intent.getStringExtra("name")
            val surname = intent.getStringExtra("surname")
            val email = intent.getStringExtra("email")
// set Strings in activity
editTextName!!.setText(name)

Make sure your ProfileActivity is added in Manifest.xml File.

CodePudding user response:

You can use GSON to parse the response.

**Create a class**

public class Codebeautify {
 Data DataObject;


 // Getter Methods 

 public Data getData() {
  return DataObject;
 }

 // Setter Methods 

 public void setData(Data dataObject) {
  this.DataObject = dataObject;
 }
}
public class Data {
 private String name;
 private String surname = null;
 private String email;
 private String phone = null;
 private String password;


 // Getter Methods 

 public String getName() {
  return name;
 }

 public String getSurname() {
  return surname;
 }

 public String getEmail() {
  return email;
 }

 public String getPhone() {
  return phone;
 }

 public String getPassword() {
  return password;
 }

 // Setter Methods 

 public void setName(String name) {
  this.name = name;
 }

 public void setSurname(String surname) {
  this.surname = surname;
 }

 public void setEmail(String email) {
  this.email = email;
 }

 public void setPhone(String phone) {
  this.phone = phone;
 }

 public void setPassword(String password) {
  this.password = password;
 }
}

**Gson gson = new Gson();
Codebeautify obj = gson.fromJson(respone, Codebeautify.class);** 
  • Related