我是新手,并试图调用库中存在的类的对象。基本上我的目标是从PHP应用程序验证用户。 com.test.app.library和该文件的代码如下:
package com.test.app.library;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import android.util.Log;
/* Helper class for sending requests to our system
* AND MANAGEMENT RESPONSE. */
public class Httppostaux {
InputStream is = null;
String result = "";
public JSONArray getserverdataMapp(ArrayList<NameValuePair> parameters,
String urlwebserver) {
httppostconnect(parameters, urlwebserver);
if (is != null) {// si obtuvo una respuesta
getpostresponse();
return getjsonarray();
} else {
return null;
}
}
// peticion HTTP
private void httppostconnect(ArrayList<NameValuePair> parametros, String urlwebserver) {
Log.e("Test","Inside post.");
//
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urlwebserver);
httppost.setEntity(new UrlEncodedFormEntity(parametros));
// ejecuto peticion enviando datos por POST
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
}
public void getpostresponse() {
// Convierte respuesta a String
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("getpostresponse", " result= " + sb.toString());
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
}
public JSONArray getjsonarray() {
// parse json data
try {
JSONArray jArray = new JSONArray(result);
return jArray;
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
return null;
}
}
}
当我尝试拨打以下代码时:
package com.test.app;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.test.app.library.Httppostaux;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.SystemClock;
import android.os.Vibrator;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
/**
* Activity which displays a login screen to the user, offering registration as
* well.
*/
public class LoginActivity extends Activity {
// private UserLoginTask mAuthTask = null;
Httppostaux post;
String URL_connect = "http://devstagemp.zerocall.com/b2c.php/pScripts/appLogin";
/**
* Keep track of the login task to ensure we can cancel it if requested.
*/
// Values for user name and password at the time of the login attempt.
private String mUserName;
private String mPassword;
private String mPincode;
// UI references.
private EditText mUserNameView;
private EditText mPasswordView;
private EditText mPincodeView;
private View mLoginFormView;
private View mLoginStatusView;
private TextView mLoginStatusMessageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// Set up the login form.
mUserNameView = (EditText) findViewById(R.id.username);
mPasswordView = (EditText) findViewById(R.id.password);
mPincodeView = (EditText) findViewById(R.id.pincode);
mPasswordView
.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int id,
KeyEvent keyEvent) {
if (id == R.id.login || id == EditorInfo.IME_NULL) {
attemptLogin();
return true;
}
return false;
}
});
mLoginFormView = findViewById(R.id.login_form);
mLoginStatusView = findViewById(R.id.login_status);
mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message);
findViewById(R.id.sign_in_button).setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View view) {
attemptLogin();
}
});
}
// @Override
// public boolean onCreateOptionsMenu(Menu menu) {
// super.onCreateOptionsMenu(menu);
// getMenuInflater().inflate(R.menu.activity_login, menu);
// return true;
// }
/**
* Attempts to sign in or register the account specified by the login form.
* If there are form errors (invalid user name, missing fields, etc.), the
* errors are presented and no actual login attempt is made.
*/
public void attemptLogin() {
// if (mAuthTask != null) {
// return;
// }
// Reset errors.
mUserNameView.setError(null);
mPasswordView.setError(null);
mPincodeView.setError(null);
// Store values at the time of the login attempt.
mUserName = mUserNameView.getText().toString();
mPassword = mPasswordView.getText().toString();
mPincode = mPincodeView.getText().toString();
boolean cancel = false;
View focusView = null;
// Check for a valid password.
if (TextUtils.isEmpty(mPassword)) {
mPasswordView.setError(getString(R.string.error_field_required));
focusView = mPasswordView;
cancel = true;
} else if (mPassword.length() < 6) {
mPasswordView.setError(getString(R.string.error_invalid_password));
focusView = mPasswordView;
cancel = true;
}
// Check for a valid user name.
if (TextUtils.isEmpty(mUserName)) {
mUserNameView.setError(getString(R.string.error_field_required));
focusView = mUserNameView;
cancel = true;
} else if (mUserName.length() < 4) {
mUserNameView.setError(getString(R.string.error_invalid_username));
focusView = mUserNameView;
cancel = true;
}
// Check for the Input
if (TextUtils.isEmpty(mPincode)) {
mPincodeView.setError(getString(R.string.error_field_required));
focusView = mPincodeView;
cancel = true;
}
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
} else {
// Show a progress spinner, and kick off a background task to
// perform the user login attempt.
mLoginStatusMessageView.setText(R.string.login_progress_signing_in);
// Authentication;
new asynclogin().execute(mUserName, mPassword,mPincode);
}
}
/**
* Shows the progress UI and hides the login form.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void showProgress(final boolean show) {
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
// for very easy animations. If available, use these APIs to fade-in
// the progress spinner.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(
android.R.integer.config_shortAnimTime);
mLoginStatusView.setVisibility(View.VISIBLE);
mLoginStatusView.animate().setDuration(shortAnimTime)
.alpha(show ? 1 : 0)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mLoginStatusView.setVisibility(show ? View.VISIBLE
: View.GONE);
}
});
mLoginFormView.setVisibility(View.VISIBLE);
mLoginFormView.animate().setDuration(shortAnimTime)
.alpha(show ? 0 : 1)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mLoginFormView.setVisibility(show ? View.GONE
: View.VISIBLE);
}
});
} else {
// The ViewPropertyAnimator APIs are not available, so simply show
// and hide the relevant UI components.
mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
/**
* Represents an asynchronous login/registration task used to authenticate
* the user.
*/
public void err_login() {
Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(200);
Toast toast1 = Toast.makeText(getApplicationContext(),
"Error:Nombre de usuario o password incorrectos",
Toast.LENGTH_SHORT);
toast1.show();
}
public boolean loginstatus(String username, String password,String pincode) {
int logstatus = -1;
/*
* Creamos un ArrayList del tipo nombre valor para agregar los datos
* recibidos por los parametros anteriores y enviarlo mediante POST a
* nuestro sistema para relizar la validacion
*/
ArrayList<NameValuePair> postparameters2send = new ArrayList<NameValuePair>();
postparameters2send.add(new BasicNameValuePair("username", username));
postparameters2send.add(new BasicNameValuePair("password", password));
postparameters2send.add(new BasicNameValuePair("pincode", pincode));
// realizamos una peticion y como respuesta obtenes un array JSON
Log.e("URL",postparameters2send.toString());
JSONArray jdata = post.getserverdataMapp(postparameters2send, URL_connect);
/*
* como estamos trabajando de manera local el ida y vuelta sera casi
* inmediato para darle un poco realismo decimos que el proceso se pare
* por unos segundos para poder observar el progressdialog la podemos
* eliminar si queremos
*/
SystemClock.sleep(950);
// si lo que obtuvimos no es null
if (jdata != null && jdata.length() > 0) {
JSONObject json_data; // creamos un objeto JSON
try {
json_data = jdata.getJSONObject(0); // leemos el primer segmento
// en nuestro caso el unico
logstatus = json_data.getInt("logstatus");// accedemos al valor
Log.e("loginstatus", "logstatus= " + logstatus);// muestro por
// log que
// obtuvimos
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// validamos el valor obtenido
if (logstatus == 0) {// [{"logstatus":"0"}]
Log.e("loginstatus ", "invalido");
return false;
} else {// [{"logstatus":"1"}]
Log.e("loginstatus ", "valido");
return true;
}
} else { // json obtenido invalido verificar parte WEB.
Log.e("JSON ", "ERROR");
return false;
}
}
class asynclogin extends AsyncTask<String, String, String> {
String user, pass,pin;
protected void onPreExecute() {
// para el progress dialog
}
protected String doInBackground(String... params) {
// obtnemos usr y pass
user = params[0];
pass = params[1];
pin = params[2];
// enviamos y recibimos y analizamos los datos en segundo plano.
if (loginstatus(user, pass,pin) == true) {
return "ok"; // login valido
} else {
return "err"; // login invalido
}
}
/*
* Una vez terminado doInBackground segun lo que halla ocurrido pasamos
* a la sig. activity o mostramos error
*/
protected void onPostExecute(String result) {
Log.e("onPostExecute=", "" + result);
if (result.equals("ok")) {
Intent i = new Intent(LoginActivity.this, DashBoard.class);
i.putExtra("user", user);
startActivity(i);
} else {
err_login();
}
}
}
}
我收到以下错误
E/AndroidRuntime(1591): FATAL EXCEPTION: AsyncTask #1
E/AndroidRuntime(1591): java.lang.RuntimeException: An error occured while executing doInBackground()
E/AndroidRuntime(1591): at android.os.AsyncTask$3.done(AsyncTask.java:278)
E/AndroidRuntime(1591): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
E/AndroidRuntime(1591): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
E/AndroidRuntime(1591): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
E/AndroidRuntime(1591): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
E/AndroidRuntime(1591): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
E/AndroidRuntime(1591): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
E/AndroidRuntime(1591): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
E/AndroidRuntime(1591): at java.lang.Thread.run(Thread.java:856)
E/AndroidRuntime(1591): Caused by: java.lang.NullPointerException
E/AndroidRuntime(1591): at com.test.app.LoginActivity.loginstatus(LoginActivity.java:237)
E/AndroidRuntime(1591): at com.test.app.LoginActivity$asynclogin.doInBackground(LoginActivity.java:295)
E/AndroidRuntime(1591): at com.test.app.LoginActivity$asynclogin.doInBackground(LoginActivity.java:1)
E/AndroidRuntime(1591): at android.os.AsyncTask$2.call(AsyncTask.java:264)
E/AndroidRuntime(1591): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
E/AndroidRuntime(1591): ... 5 more
互联网权限存在于android清单文件中。
答案 0 :(得分:0)
您在LoginActivity.java上有一个NPE:确保所有参数都不为空,并确保它们是属性配置 BEFORE ,您将它们传入。
答案 1 :(得分:0)
post
为空。记得在访问它之前实例化它。