doushun1870 2017-02-02 18:54
浏览 87

Android(java)凌空不发送帖子请求

After reading MANY posts that seem similar, these were all about JSON requests, not StringRequests. I am using volley API for my Android application, and I am following a tutorial on interaction between my app using volley and my server which is handled with php. For some reason however, my data is not sent to the php part, because when I try to access the data on the webserver, it states that the variables are empty.

Here is my project. First off is my Singleton class which sets up ONE requestqueue:

import android.content.Context;

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


public class Server_singleton
{
    private static Server_singleton anInstance;
    private RequestQueue requestQueue;
    private static Context aCtx;

    private Server_singleton(Context context)
    {
        aCtx = context;
        requestQueue = getRequestQueue();
    }

    public static synchronized Server_singleton getInstance(Context context)
    {
        if(anInstance == null)
        {
            anInstance = new Server_singleton(context);
        }
        return anInstance;
    }

    public RequestQueue getRequestQueue()
    {
        if(requestQueue == null)
        {
            requestQueue = Volley.newRequestQueue(aCtx.getApplicationContext());
        }
        return requestQueue;
    }

    public <T> void addToRequestQueue(Request<T> request)
    {
        requestQueue.add(request);
    }

}

This above class should be all nice and fine I believe(99% certain), since I follow a general design approach recommended by Android/Google using volley.

Secondly, the next file which uses Server_singleton. Here is where the magic happens, and most likely the mistake is in here some place:

import android.content.Context;
import android.util.Log;

import com.android.volley.AuthFailureError;
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.StringRequest;
import com.android.volley.toolbox.Volley;

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

/**
 * 
 *
 * This class handles requests to web server by using Google Volley API
 * Google Volley API is very powerful and abstracts many low-level details when establishing
 * connection with a web server.
 * Volley API does not run on the main thread, which is the correct way of doing it in android.
 * If it was not doing work in a background thread, the main thread would be blocked(perhaps).
 * This is all done in an asynchronous way, which means that methods may behave somewhat
 * different than you would expect. A method which returns a string for example
 * may return a null object, before it is actually done waiting on the response from server
 * This means that we have to introduce callback methods with for instance interfaces.
 */


public class Server_interaction
{
    String server_url = "http://hiddenfromyou/update_location.php"; //correct ip in my code, but hidden here
    String response_string;
    RequestQueue queue;
    Context context;

    public Server_interaction(Context context)
    {
         this.context = context;
         queue = Server_singleton.getInstance(context).getRequestQueue();
    }


    public static final String TAG = Server_interaction.class.getSimpleName();

    public void post_request(final VolleyCallback callback)
    {
        StringRequest stringRequest = new StringRequest(Request.Method.POST, server_url,
                new Response.Listener<String>()
                {
                    @Override
                    public void onResponse(String response)
                    {
                        response_string = response;
                        callback.onSuccess(response_string);
                        //requestQueue.stop();
                        Log.i(TAG, "the response is: "+ response_string);

                    }
                }
                , new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error){
                        response_string = "Something went wrong";
                        //error.printstacktrace()
                        //requestQueue.stop();
                        Log.i(TAG, "something went wrong. Is the server up and running?");
                    }

                })
        {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {

                String the_name = "olaf";
                String the_mail = "lalalal";
                String the_country = "Norway";
                String the_latitude = "33";
                String the_longitude = "99";


                Map<String, String> params = new HashMap<String, String>();
                params.put("name", the_name);
                params.put("email", the_mail);
                params.put("country", the_country);
                params.put("latitude", String.valueOf(the_latitude));
                params.put("longitude", String.valueOf(the_longitude));

                Log.i(TAG, "inside getparams : "+params);
                return params;
            }
        };//stringrequest parameter end

        //add request to requestqueue
        Log.i(TAG, "the stringrequest: "+ stringRequest);
        Server_singleton.getInstance(context).addToRequestQueue(stringRequest);
        Log.i(TAG, "the response again:: "+ response_string);


    }

}

The above code WORKS. But it should POST country, latitute etc to my webserver...

Here is my PHP script:

<?php

$email = isset($_POST["email"]) ? $_POST["email"] : print("received nothing!");               //receive from android app
$phonenumber = $_POST["phonenumber"]; //receive from android app
$country = $_POST["country"];         //receive from android app
$latitude = $_POST["latitude"];       //receive from android app
$longitude = $_POST["longitude"];   

$username_for_localhost = "root";
$password_for_localhost = "";
$host = "localhost";
$db_name = "exigentia_location_db";

$con = mysqli_connect($host, $username_for_localhost, $password_for_localhost, $db_name);

if($con)
{
    echo "Connection succeded";
}

else
{
    echo "Connection failed";
}


$sql = "insert into person values('".$email."', '".$phonenumber."', '".$country."', '".$location."', '".$latitude."', '".$longitude."');";

if(mysqli_query($con, $sql))
{
    echo "data insertion succeeded";
}

else
{
    echo "data insertion failed";
}




mysqli_close($con);

?>

I check only the first var if its set, and else print out. It prints out the text, which means it is not set...Also the other ones give me index errors, since they obviously are empty...

What am I doing wrong? I have been fiddling with this problem for days, and I cannot figure out where I am wrong.

Finally a pic of what happens when I refresh my page with the php script after running the app:

php_problem

  • 写回答

4条回答 默认 最新

  • dthhlf1777 2017-02-02 19:56
    关注

    try this:

    Server_singleton.getInstance().addToRequestQueue(request, method);
    

    where method is your tag: like "Register", "login" ..etc.You can use without Tag method also.

    Now in your Server_singleton write this code:

     public class Server_singleton extends Application {
    
    
        public static final String TAG = Server_singleton.class.getSimpleName();
    
        private RequestQueue mRequestQueue;
        private static Server_singleton mInstance;
    
        @Override
        public void onCreate() {
            super.onCreate();
            mInstance = this;
        }
    
        public static synchronized Server_singleton getInstance() {
            return mInstance;
        }
    
        public RequestQueue getRequestQueue() {
            if (mRequestQueue == null) {
                mRequestQueue = Volley.newRequestQueue(getApplicationContext());
            }
    
            return mRequestQueue;
        }
    
        public <T> void addToRequestQueue(Request<T> req, String tag) {
            req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
            getRequestQueue().add(req);
        }
    
        public <T> void addToRequestQueue(Request<T> req) {
            req.setTag(TAG);
            getRequestQueue().add(req);
        }
    
        public void cancelPendingRequests(Object tag) {
            if (mRequestQueue != null) {
                mRequestQueue.cancelAll(tag);
            }
        }
    }
    

    Make sure you set the permission in manifest:

    <uses-permission android:name="android.permission.INTERNET" />
    

    And in build.gradle use:

     compile 'com.mcxiaoke.volley:library-aar:1.0.0'
    
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog