在Android

时间:2018-06-14 07:42:25

标签: android android-service android-volley

我在android工作室创建了一个新服务,并试图实现一个通用的Volley请求。创建RequestQueue时出错。我知道我对这个上下文做错了,不知道我到底犯了什么错误。

我从 MainActivity 调用 volleyPost(),如下所示。

MainActivity.java

import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

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

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

public class MainActivity extends AppCompatActivity {

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

        final Button login = (Button) findViewById(R.id.CompanyLogin);
        final EditText companyName = (EditText) findViewById(R.id.CompanyName);
        final EditText companyPassword = (EditText) findViewById(R.id.CompanyPassword1);

        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(companyName.getText().toString().isEmpty()){
                    Toast.makeText(MainActivity.this, "Company ID is empty", Toast.LENGTH_LONG).show();
                }
                else if(companyPassword.getText().toString().isEmpty()){
                    Toast.makeText(MainActivity.this, "Password is empty", Toast.LENGTH_LONG).show();
                }
                else{
                    companyLogin(companyName.getText().toString(), companyPassword.getText().toString());
                }
            }
        });

    }

    public interface VolleyCallback {
        void onSuccess(String result);
    }

    public void companyLogin(String companyname, String password) {
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        String URL = "http://...";
        final Map<String, String> params = new HashMap<String, String>();
        params.put("name", companyname);
        params.put("pwd", password);

        VolleyAPIService volleyAPIService = new VolleyAPIService();
        volleyAPIService.volleyPost(new VolleyCallback() {
            @Override
            public void onSuccess(String result) {
                //do stuff here
                Log.d("VOLLEY", "onSuccess: " + result);
                if(!result.isEmpty()){
                    Intent userLoginActivity = new Intent(MainActivity.this, UserLogin.class);
                    startActivity(userLoginActivity);
                }
                else{
                    AlertDialog.Builder login_failed = new AlertDialog.Builder(MainActivity.this);
                    login_failed.setMessage("Login Failed, invalid credentials")
                            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                }
                            });
                    AlertDialog alert = login_failed.create();
                    alert.show();
                }
            }
        }, URL, params);
    }
}

VolleyAPIService.java

import android.content.DialogInterface;
import android.content.Intent;
import android.os.IBinder;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.app.Service;
import android.widget.Toast;

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;

public class VolleyAPIService extends Service {
    public VolleyAPIService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    public void volleyPost(final MainActivity.VolleyCallback callback, String URL, Map<String, String> param) {
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        final Map<String, String> params = param;

        StringRequest stringRequest = new StringRequest(Request.Method.POST, URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        callback.onSuccess(response);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                    }
                }) {
            @Override
            protected Map<String, String> getParams() {;
                return params;
            }
        };
        requestQueue.add(stringRequest);
    }
}

错误信息如下。

E / AndroidRuntime:致命异常:主要                   处理:com.example.alfatkgindia.sample1,PID:22875                   java.lang.NullPointerException:尝试在空对象引用上调用虚方法'java.io.File android.content.Context.getCacheDir()'                       在android.content.ContextWrapper.getCacheDir(ContextWrapper.java:262)                       在com.android.volley.toolbox.Volley.newRequestQueue(Volley.java:89)                       在com.android.volley.toolbox.Volley.newRequestQueue(Volley.java:67)                       在com.android.volley.toolbox.Volley.newRequestQueue(Volley.java:102)                       在com.example.alfatkgindia.sample1.VolleyAPIService.volleyPost(VolleyAPIService.java:32)                       在com.example.alfatkgindia.sample1.MainActivity.companyLogin(MainActivity.java:99)                       at com.example.alfatkgindia.sample1.MainActivity $ 1.onClick(MainActivity.java:54)                       在android.view.View.performClick(View.java:6305)                       在android.view.View $ PerformClick.run(View.java:24840)                       在android.os.Handler.handleCallback(Handler.java:790)                       在android.os.Handler.dispatchMessage(Handler.java:99)                       在android.os.Looper.loop(Looper.java:164)                       在android.app.ActivityThread.main(ActivityThread.java:6501)                       at java.lang.reflect.Method.invoke(Native Method)                       在com.android.internal.os.RuntimeInit $ MethodAndArgsCaller.run(RuntimeInit.java:438)                       在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

1 个答案:

答案 0 :(得分:0)

您的上下文为null,因为您实例化了一项服务。您不能只是实例化服务。您让框架为您完成。如果要启动服务,请使用startService方法。

如果您打算在后台线程中运行login方法,除了service之外还有其他选择。您可以使用AsyncTask或AsyncLoaders。