how to fetch single data from server into textview

2019-09-08 02:39发布

问题:

i am new to android ,i am working on login and password activity where if you forgot the password then after typing your correct email the server will send the password into textview which should be set as settext.i made the php file but i am unable to made coding in android ..i want the data through volley . here is my php file:

<?php 

include ('config.php');

$sql = "SELECT * FROM UserInfo WHERE email='".$email."'";



$r = mysqli_query($con,$sql);

$result = array();

while($row = mysqli_fetch_array($r)){
    array_push($result,array(
        'password'=>$row['password'],

    ));
}

echo json_encode(array('result'=>$result));

mysqli_close($con);

?>

here is my ForgotPassword Activity:

     public class ForgotPasswordActivity extends AppCompatActivity {

    private String fremail;
    private ProgressDialog pDialog;
    protected EditText femail;
    protected Button mSubmitButton;
    TextView pas;

    private static String url_create_book = "http://cloud.....com/broccoli/fpassword.php";




     @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forgot_password);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);



          pas=(TextView)findViewById(R.id.pas) ;
          femail=(EditText)findViewById(R.id.feml);

          Button submit= (Button) findViewById(R.id.sbtn);
          submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                pDialog = new ProgressDialog(ForgotPasswordActivity.this);
                pDialog.setMessage("Please wait..");
                pDialog.setIndeterminate(false);
                pDialog.setCancelable(true);
                pDialog.show();
                fremail = femail.getText().toString();



                // new CreateNewProduct().execute();
                StringRequest stringRequest = new StringRequest(Request.Method.POST, url_create_book,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {
                                pDialog.dismiss();

                                try {
                                    JSONObject object     = new JSONObject(response);
                                    JSONArray jsonArray   = object.getJSONArray("result");
                                    JSONObject jsonObject = jsonArray.getJSONObject(0);

// fetch password from JSON
                                    String password         = jsonObject.getString("password");
// use password in textviewfemail.setText(password, TextView.BufferType.EDITABLE);
                                    pas.setText(password, TextView.BufferType.EDITABLE);



                                }
                                catch (JSONException e) {
                                    Toast.makeText(ForgotPasswordActivity.this, e.toString(), Toast.LENGTH_LONG).show();
                                }


                            }

                        },

                        new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {
                                pDialog.dismiss();
                                Toast.makeText(ForgotPasswordActivity.this, error.toString(), Toast.LENGTH_LONG).show();
                            }
                        }) {
                    @Override
                    protected Map<String, String> getParams() {
                        Map<String, String> params = new HashMap<String, String>();
                        params.put("email", fremail);


                        return params;
                    }
                };
                RequestQueue requestQueue = Volley.newRequestQueue(ForgotPasswordActivity.this);
                requestQueue.add(stringRequest);

            }

        });
    }








    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

}

here is my xml :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.zeba.broccoli.Login">

    <!-- Login progress -->
    <LinearLayout
        android:gravity="center_horizontal"
        android:orientation="vertical"
        android:id="@+id/login_form"
        android:layout_width="match_parent"
        android:layout_height="match_parent">


        <ImageView android:src="@drawable/logobr"
            android:layout_width="wrap_content"
            android:layout_height="72dp"
            android:layout_marginTop="40dp"
            android:layout_gravity="center_horizontal" />





        <LinearLayout
            android:id="@+id/email_login_form"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:orientation="vertical">





            <android.support.design.widget.TextInputLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content">






                <AutoCompleteTextView
                    android:id="@+id/feml"
                    android:layout_width="match_parent"

                    android:hint="email"
                    android:inputType="textEmailAddress"
                    android:maxLines="1"
                    android:singleLine="true"
                    android:background="@drawable/rounded_edittext"

                    android:layout_height="40dp"
                    android:paddingLeft="5dp"

                    android:layout_marginBottom="20dip"/>

            </android.support.design.widget.TextInputLayout>


          </LinearLayout>



            <Button
                android:id="@+id/sbtn"
                style="?android:textAppearanceSmall"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="16dp"
                android:text="Submit"
                android:background="@drawable/mybutton"

                android:textColor="#fff"
                android:textStyle="bold"
                android:elevation="0dp" />

            <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:orientation="horizontal"
                android:weightSum="1" >
                <TextView
                    android:id="@+id/fpss"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="0.5"
                    android:gravity="center"
                    android:layout_marginTop="16dp"
                    android:text="Your Password is:" />
                <TextView
                    android:id="@+id/pas"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="0.5"
                    android:gravity="center"
                    android:layout_marginTop="16dp"


                    />

I am not getting any error in logcat but when i run it on device it shows

jsonException....Index 0 out of 0 range[0...0]

回答1:

Your PHP code is sending password in JSON format, first decode the JSON in your code and fetch the password:

new Response.Listener<String>() {
@Override
public void onResponse(String response) {
pDialog.dismiss();

try {
JSONObject object     = new JSONObject(response);
JSONArray jsonArray   = object.getJSONArray("result");
JSONObject jsonObject = jsonArray.getJSONObject(0);

// fetch password from JSON
// UPDATED HERE
String password         = jsonObject.getString("password");

femail.setText(password, TextView.BufferType.EDITABLE);

} 
catch (JSONException e) {
Toast.makeText(getContext(), e.toString(), Toast.LENGTH_LONG).show();
}  

},

PHP

<?php 

include ('config.php');

// updated here, value is mapped 
$email = $_POST['email'];

$sql = "SELECT * FROM UserInfo WHERE email='".$email."'";



$r = mysqli_query($con,$sql);

//checking if email is valid or not
if(mysqli_fetch_array($r) == NULL){
echo "Invalid email";
}
else{
$result = array();

while($row = mysqli_fetch_array($r)){
    array_push($result,array(
        'password'=>$row['password'],

    ));
}
echo json_encode(array('result'=>$result));
}
mysqli_close($con);

?>


回答2:

use JsonObjectRequest instead of StringRequest

    JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, json, new Response.Listener<JSONObject>() {
                            @Override
                            public void onResponse(JSONObjectresponse) {
                          // you code here
 }
}
, new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {

                            }
                        }) {
                    @Override
                    public Map<String, String> getHeaders() throws AuthFailureError {
                        Map<String, String> headers = new HashMap<String, String>();
                    // add your header here
                        return headers;
                    }
                };