从JSON响应中提取数据



我试图从kotlin中php的JSON响应中提取数据。这是我的php的结果:

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

但是当我访问这个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)

我想提取数据从我的json创建数组或arrayList发送这个数组到我的活动。但是我不知道如何访问这个JSON。

这个功能,它是登录在我的应用程序:

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)
}

我解决与评论在这个线程。现在我尝试从bundle

设置文本我´m做:

private var editTextName: EditText? = null
editTextName = findViewById<EditText>(R.id.userName)
// set Strings in activity
editTextName!!.setText(name)

但是android studio返回一个空指针异常。检查我的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" />

我的错误:

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

在我的setText中它是我的错误。我不知道我做错了。

更新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)*/
}

但我有一个空指针在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" />

此字段在log android studio中为null。我不知道我做错了什么。也许我没有说我的EditText它在fragments

更新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)
}
}

概要文件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

感谢自述,抱歉我的英语不好

您错过了"data"JSONObject从json。您需要添加Response和data 2 JSONObjects。我在你的代码中添加了一行代码并更改了对象参数。

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)}

As per your Update

在您的成功响应传递值

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()

和你的ProfileActivity得到的值,你从第一活动传递。

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

确保你的ProfileActivity被添加到Manifest.xml文件中。

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);** 

最新更新