1

我已经创建了一个 Android 应用程序,但是当我在我的真实设备上运行它时它崩溃了,我在我的 logcat 中得到了这个:

05-20 17:32:50.251: E/SensorManager(20804): thread start
05-20 17:32:50.376: E/SpannableStringBuilder(20804): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
05-20 17:32:50.376: E/SpannableStringBuilder(20804): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
05-20 17:33:01.411: E/JSON Parser(20804): Error parsing data org.json.JSONException: End of input at character 0 of 
05-20 17:33:01.416: E/AndroidRuntime(20804): FATAL EXCEPTION: main
05-20 17:33:01.416: E/AndroidRuntime(20804): java.lang.NullPointerException
05-20 17:33:01.416: E/AndroidRuntime(20804):    at com.mohammed.watzIslam.LoginActivity$1.onClick(LoginActivity.java:62)
05-20 17:33:01.416: E/AndroidRuntime(20804):    at android.view.View.performClick(View.java:4211)
05-20 17:33:01.416: E/AndroidRuntime(20804):    at android.view.View$PerformClick.run(View.java:17267)
05-20 17:33:01.416: E/AndroidRuntime(20804):    at android.os.Handler.handleCallback(Handler.java:615)
05-20 17:33:01.416: E/AndroidRuntime(20804):    at android.os.Handler.dispatchMessage(Handler.java:92)
05-20 17:33:01.416: E/AndroidRuntime(20804):    at android.os.Looper.loop(Looper.java:137)
05-20 17:33:01.416: E/AndroidRuntime(20804):    at android.app.ActivityThread.main(ActivityThread.java:4898)
05-20 17:33:01.416: E/AndroidRuntime(20804):    at java.lang.reflect.Method.invokeNative(Native Method)
05-20 17:33:01.416: E/AndroidRuntime(20804):    at java.lang.reflect.Method.invoke(Method.java:511)
05-20 17:33:01.416: E/AndroidRuntime(20804):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
05-20 17:33:01.416: E/AndroidRuntime(20804):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
05-20 17:33:01.416: E/AndroidRuntime(20804):    at dalvik.system.NativeStart.main(Native Method)

这是我使用的 JSON 解析器类:

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {
        super();
    }

    public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        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();
            json = sb.toString();
            Log.e("JSON", json);
        } catch (Exception e) {
            //Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;
    }
}

这是用户函数(带有 Web 服务地址):

public class UserFunctions {

    private JSONParser jsonParser;

    private static String loginURL = "http://my pc lan adress/android_login_api/include/DB_functions";
    private static String registerURL = "http://my pc lan adress/android_login_api/include/DB_functions";

    private static String login_tag = "login";
    private static String register_tag = "register";

    // constructor
    public UserFunctions() {
        jsonParser = new JSONParser();
    }

    /**
    * function make Login Request
    * @param email
    * @param password
    * */
    public JSONObject loginUser(String email, String password) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("tag", login_tag));
        params.add(new BasicNameValuePair("email", email));
        params.add(new BasicNameValuePair("password", password));
        JSONObject json = jsonParser.getJSONFromUrl(loginURL, params);
        // return json
        // Log.e("JSON", json.toString());
        return json;
    }

    /**
    * function make reg. Request
    * @param name
    * @param email
    * @param password
    * */
    public JSONObject registerUser(String name, String password, String email) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("tag", register_tag));
        params.add(new BasicNameValuePair("name", name));
        params.add(new BasicNameValuePair("email", email));
        params.add(new BasicNameValuePair("password", password));

        // getting JSON Object
        JSONObject json = jsonParser.getJSONFromUrl(registerURL, params);
        // return json
        return json;
    }

    /**
    * Function get Login status
    * */
    public boolean isUserLoggedIn(Context context) {
        DatabaseHandler db = new DatabaseHandler(context);
        int count = db.getRowCount();
        if (count > 0) {
            // user logged in
            return true;
        }
        return false;
    }

    /**
    * Function to logout user
    * Reset Database
    * */
    public boolean logoutUser(Context context) {
        DatabaseHandler db = new DatabaseHandler(context);
        db.resetTables();
        return true;
    }
}

这是用户 login.java

package com.mohammed.watzIslam;

import java.util.HashMap;

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

import com.mohammed.watzIslam.library.DatabaseHandler;
import com.mohammed.watzIslam.library.UserFunctions;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;



public class LoginActivity extends Activity {
Button btnLogin;
Button btnLinkToRegister;
EditText inputEmail;
EditText inputPassword;
TextView loginErrorMsg;

// JSON Response node names
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_UID = "id";
private static String KEY_NAME = "name";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);

// Importing all assets like buttons, text fields
inputEmail = (EditText) findViewById(R.id.loginEmail);
inputPassword = (EditText) findViewById(R.id.loginPassword);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
loginErrorMsg = (TextView) findViewById(R.id.login_error);

// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {

public void onClick(View view) {
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
UserFunctions userFunction = new UserFunctions();
Log.d("Button", "Login");
JSONObject json = userFunction.loginUser(email, password);

// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
loginErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS); 
if(Integer.parseInt(res) == 1){
// user successfully logged in
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");


// Launch Dashboard Screen
Intent applicationinterface = new Intent(getApplicationContext(), Appinterface.class);

// Close all views before launching Dashboard
applicationinterface.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(applicationinterface);

// Close Login Screen
finish();
}else{
// Error in login
loginErrorMsg.setText("Incorrect username/password");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});

// Link to Register Screen
btnLinkToRegister.setOnClickListener(new View.OnClickListener() {

public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
finish();
}
});
}
}

这是用户 register.java

package com.mohammed.watzIslam;

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

import com.mohammed.watzIslam.library.DatabaseHandler;
import com.mohammed.watzIslam.library.UserFunctions;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class RegisterActivity extends Activity {
Button btnRegister;
Button btnLinkToLogin;
EditText inputFullName;
EditText inputEmail;
EditText inputPassword;
TextView registerErrorMsg;

// JSON Response node names
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_UID = "id";
private static String KEY_NAME = "name";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);

/*StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);*/

// Importing all assets like buttons, text fields
inputFullName = (EditText) findViewById(R.id.registerName);
inputEmail = (EditText) findViewById(R.id.registerEmail);
inputPassword = (EditText) findViewById(R.id.registerPassword);
btnRegister = (Button) findViewById(R.id.btnRegister);
btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);
registerErrorMsg = (TextView) findViewById(R.id.register_error);

// Register Button Click event
btnRegister.setOnClickListener(new View.OnClickListener() {         
public void onClick(View view) {
String name = inputFullName.getText().toString();
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.registerUser(name, email, password);

// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
registerErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS); 
if(Integer.parseInt(res) == 1){
// user successfully registred
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");


// Launch Dashboard Screen
Intent applicationinterface = new Intent(getApplicationContext(), Appinterface.class);
// Close all views before launching Dashboard
applicationinterface.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(applicationinterface);
// Close Registration Screen
finish();
}else{
// Error in registration
registerErrorMsg.setText("Error occured in registration");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});

// Link to Login Screen
btnLinkToLogin.setOnClickListener(new View.OnClickListener() {

public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
LoginActivity.class);
startActivity(i);
// Close Registration View
finish();
}
});
}
}

Web 服务目前在 PHP 中实现,并从我本地 PC 上的 XAMMP 服务器运行。基本上,他们只是从 MySQL 数据库中获取数据并提供用户注册/用户登录/网站功能。

该设备通过 WiFi 从我的电脑“使用 connectify”连接到互联网。

我一直在努力寻找答案,但没有取得多大成功(我是一名新开发人员,使用了很多来自互联网的代码,并进行了一些修改)。任何和所有的帮助表示赞赏。

4

0 回答 0