0

昨年、Android アプリケーションを作成しましたが、問題なく動作し、アプリケーションの開発を担当するようになりました。

しかし、ユーザーの登録は機能しなくなりました。その理由は、私には手がかりがありません。

これが私の開始画面で、ユーザーが登録するアクティビティです。

public class Prompt extends Activity {

    public EditText u, p, e;
    public String username, password, emailadd;
    public Button createClient;
    final Context context = this;
    public TextView registerErrorMsg;

    // JSON Response node names
    private static String KEY_SUCCESS = "success";
    @SuppressWarnings("unused")
    private static String KEY_ERROR = "error";
    @SuppressWarnings("unused")
    private static String KEY_ERROR_MSG = "error_msg";
    private static String KEY_UID = "uid";
    private static String KEY_NAME = "name";
    private static String KEY_EMAIL = "email";
    private static String KEY_CREATED_AT = "created_at";

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.prompt);
        // Importing all assets like buttons, text fields

        u = (EditText) findViewById(R.id.username);
        p = (EditText) findViewById(R.id.Password);
        e = (EditText) findViewById(R.id.emailAddress);
        createClient = (Button) findViewById(R.id.createClient);
        registerErrorMsg = (TextView) findViewById(R.id.register_error);
        u.setText("usernametest");
        p.setText("passwordtest");
        e.setText("TEST@gmail.com");

        //Toast.makeText(getApplicationContext(), "...", Toast.LENGTH_LONG).show();

        createClient.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                username = u.getText().toString();
                password = p.getText().toString();
                emailadd = e.getText().toString();
                UserFunctions userFunction = new UserFunctions();

                //Toast.makeText(getApplicationContext(), username+" "+password+" "+emailadd, Toast.LENGTH_LONG).show();

                //now we have text input, validate them
                if(username.length() < 5 || password.length() < 5 || emailadd.length() < 5){
                    //minimum input for each field is > 5 characters
                    registerErrorMsg.setText("Username, password and email must have must than 5 characters");
                }
                else{
                    //if validated correctly upload
                    JSONObject json = userFunction.registerUser(username, emailadd, password);
                    Log.e("JSON RESULT", "JSON result: " + json);

                    //successfully make the check file and redirect to the homepage
                    try {
                            String FILE_NAME = "filename.txt";
                            FileOutputStream fos = openFileOutput(FILE_NAME, Context.MODE_WORLD_READABLE);
                            try{
                                fos.write(username.getBytes());
                            }catch (IOException e){
                                e.printStackTrace();
                            }
                            fos.close();

                            //if all complete, redirect to home page
                            Intent intent2 = new Intent(Prompt.this, StrategicEnergyActivity.class);
                            intent2.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            startActivity(intent2);
                            finish();
                    } 
                    catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } 
                    catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }
}

以下は、Web サービスから返された JSON を処理する JSON パーサー クラスです。

public class JSONParser {

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

    // constructor
    public JSONParser() {
    }

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

        Log.e("TESTTTT", " " + params.get(0) + " " + params.get(1) + " " + params.get(2)  + " " + params.get(3));
        // Making HTTP request
        try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
            httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

            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);
            }
            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;
    }
}

これは、データ処理/メソッド呼び出しを行うクラスである私のユーザー関数クラスです。

public class UserFunctions {

    private JSONParser jsonParser;

    private static String registerURL = "http://www.website.com/api/index.php?";
    private static String register_tag = "register";

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

    /**
     * function make Login Request
     * @param name
     * @param email
     * @param password
     * */
    public JSONObject registerUser(String name, String email, String password){
        // 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));

        Log.e("Credentials", "Username: " + name + "\nEmail: " + email + "\nPassword: " + password);
        //Toast.makeText(getParent(), name+" "+email+" "+password, Toast.LENGTH_LONG).show();

        JSONObject json = jsonParser.getJSONFromUrl(registerURL, params);
        return json;
    }
}

私のWebサービスのコードは次のとおりです。

<?php
    print_r($_POST);
    $tag = "register";

    // include db handler
    require_once 'include/DB_Functions.php';
    $db = new DB_Functions();

    // response Array
    $response = array("tag" => $tag, "success" => 0, "error" => 0);

    // check for tag type
    if ($tag == 'register') {
        // Request type is Register new user
        $name = $_POST['name'];
        $email = $_POST['email'];
        $password = $_POST['password'];

        // check if user is already existed
        if($db->isUserExisted($email)){
            // user is already exists - error response
            $response["error"] = 2;
            $response["error_msg"] = "User Already Exists";
            echo json_encode($response). "User Already Exists";
        } 
        else{       
            // store user
            $user = $db->storeUser($name, $email, $password);

            if($user){
                // user stored successfully
                $response["success"] = 1;
                $response["uid"] = $user["unique_id"];
                $response["user"]["name"] = $user["name"];
                $response["user"]["email"] = $user["email"];
                $response["user"]["created_at"] = $user["created_at"];
                $response["user"]["updated_at"] = $user["updated_at"];
                echo json_encode($response). "User Stored Successfully";
            } 
            else{
                // user failed to store
                $response["error"] = 1;
                $response["error_msg"] = "Error occured in Registration";
                echo json_encode($response);
            }
        }
    } 
    else{
        echo "Invalid Request";
    }
?>

最後に、これは現在スローされているエラーです。JSONParser クラスの sb.append(line) 行で発生します。

05-21 16:35:46.304: E/Buffer Error(4278): Error converting result java.lang.NullPointerException
05-21 16:35:46.308: E/JSON Parser(4278): Error parsing data org.json.JSONException: End of input at character 0 of 
05-21 16:35:46.308: E/JSON RESULT(4278): JSON result: null

ここで私が間違っていることを誰かが見つけることができますか? どんなことでもお役に立てれば幸いです。

前もって感謝します!

4

1 に答える 1