java - 我如何从数据库中检索数据并将该数据传递到下一个 Activity

标签 java android

how should i post this one in next activity by clicking the button Retrieve

但我不知道如何编写代码,我使用的是在线数据库 000webhost。我的问题是,当我单击检索按钮时,它将在下一个 Activity 中发布数据库的内容,这是来自 MainActivity.class 的 print.class 这是我目前的代码

MainActivity.class

package com.example.child.retrieve;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.android.volley.NetworkResponse;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.Volley;
import com.example.child.retrieve.LoginRequest;
import com.example.child.retrieve.R;
import com.example.child.retrieve.print;

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

import java.io.UnsupportedEncodingException;

public class MainActivity extends AppCompatActivity {

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

        final Button bLogin = (Button)findViewById(R.id.ret);


        bLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                Response.Listener<String> responseListener = new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        try {
                            JSONObject jsonResponse = new JSONObject(response);
                            boolean success = jsonResponse.getBoolean("success");

                            if(success) {

                                Intent intent = new Intent(MainActivity.this, print.class);
                                MainActivity.this.startActivity(intent);


                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                };


                LoginRequest loginRequest = new LoginRequest(responseListener);
                RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
                queue.add(loginRequest);

            }
        });
    }


    /* import com.android.volley.toolbox.HttpHeaderParser; */
    public void onErrorResponse(VolleyError error) {

        // As of f605da3 the following should work
        NetworkResponse response = error.networkResponse;
        if (error instanceof ServerError && response != null) {
            try {
                String res = new String(response.data,
                        HttpHeaderParser.parseCharset(response.headers, "utf-8"));
                // Now you can use any deserializer to make sense of data
                JSONObject obj = new JSONObject(res);
            } catch (UnsupportedEncodingException e1) {
                // Couldn't properly decode data to string
                e1.printStackTrace();
            } catch (JSONException e2) {
                // returned data is not JSONObject?
                e2.printStackTrace();
            }
        }
    }
}

主 Activity .xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.child.retrieve.MainActivity">

    <Button
        android:id="@+id/ret"
        android:text="Retrieve"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</android.support.constraint.ConstraintLayout>

正在加载数据库的 LoginRequest.class

package com.example.child.retrieve;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Child on 1/31/2017.
 */

public class LoginRequest extends StringRequest {

    private static final String LOGIN_REQUEST_URL = "http://cedportfolio.000webhostapp.com/Login.php";
    private Map<String, String> params;

    public LoginRequest(Response.Listener<String> listener) {
        super(Request.Method.POST, LOGIN_REQUEST_URL, listener, null);
        params = new HashMap<>();

    }
    @Override
    public Map<String, String> getParams() {

        return params;
    }
}

打印类

package com.example.child.retrieve;

import android.app.Activity;
import android.os.Bundle;

/**
 * Created by Child on 7/21/2017.
 */

public class print extends Activity {

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

最佳答案

如果您想将数据从一个 Activity 传递到另一个 Activity ,您需要创建一个 Parcelable 对象。检查this answer

你会需要这样的东西:

public class MyData implements Parcelable {
    ...
}

解析响应并将其传递给新 Activity

MyData data = parseJson(jsonResponse)
Intent intent = new Intent(MainActivity.this, print.class);
intent.putParcelable("data", data);
MainActivity.this.startActivity(intent);

在新的 Activity 中恢复它

public class print extends Activity {

    ...
    MyData data = getIntent().getParcelableExtra("data");
    ...
}

请注意,在 Activity 之间传递大对象可能会降低性能。您应该考虑其他策略,例如传递一些 ID 并在“接收方” Activity 中获取数据

关于java - 我如何从数据库中检索数据并将该数据传递到下一个 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45230164/

相关文章:

java - Checkstyle 和 PMD 仅作为建议

android - 在 Android 版 Adob​​e AIR 上调用电话

Android P - 从 Assets 复制数据库后出现 'SQLite: No Such Table Error'

android - 如何单独加载部分布局内容

Android getapplicationContext() 处的 Java.lang.NullPointerException

Java将负数转为0

c# - java是否像c#一样支持显式接口(interface)实现?

java - JNDI 定义中的额外信息

android - 使用自定义可绘制拇指时如何保持切换拇指阴影/高程?

java - Wicket 口 : how to set checked value in CheckBoxMultipleChoice