Попытка вызвать виртуальный метод «void android.widget.TextView.setText (java.lang.CharSequence)» для нулевого объекта referenceProfileFragment.java:43) - PullRequest
0 голосов
/ 26 февраля 2019

Вот мой менеджер предпочтений акций

package com.example.call_for_help.storage;

import android.content.Context;
import android.content.SharedPreferences;

import com.example.call_for_help.models.Helper;
import com.example.call_for_help.models.Requestor;

public class SharedPrefManager {
    private static final String SHARED_PREF_NAME="my_shared_preff";
    private static SharedPrefManager mInstance;
    private Context mcCtx;

    private SharedPrefManager(Context mcCtx){
        this.mcCtx=mcCtx;
    }
    public static synchronized SharedPrefManager getIntance(Context mCtx){
        if(mInstance==null){
            mInstance=new SharedPrefManager(mCtx);
        }
        return mInstance;
    }

    //User uses the class of User and "user" is the object so it can access to the function and use User's model
    public void savehelper(Helper helper){
        SharedPreferences sharedPreferences = mcCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor=sharedPreferences.edit();
        editor.putInt("id",helper.getHelper_id());
        editor.putFloat("rating",helper.getHelper_rating());
        editor.putString("student_id",helper.getHelper_student_id());
        editor.putString("name",helper.getHelper_name());
        editor.putString("email",helper.getHelper_email());
        editor.putString("phone",helper.getHelper_phone());
        editor.putString("gender",helper.getHelper_gender());
        editor.putString("category",helper.getHelper_category());
        editor.putString("description",helper.getHelper_description());
        editor.apply();
        editor.commit();
    }


    public void saverequestor(Requestor requestor){
        SharedPreferences sharedPreferences = mcCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor=sharedPreferences.edit();
        editor.putInt("id",requestor.getRequestor_id());
        editor.putString("student_id",requestor.getRequestor_student_id());
        editor.putString("name",requestor.getRequestor_name());
        editor.putString("email",requestor.getRequestor_email());
        editor.putString("phone",requestor.getRequestor_phone());
        editor.putString("gender",requestor.getRequestor_gender());
        editor.apply();
        editor.commit();

    }

    public boolean isLoggedIn(){
        SharedPreferences sharedPreferences = mcCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
        //if id=="1" means not login (false)
        //if id!="-1" means logged in (true)
        return sharedPreferences.getInt("id",-1)!=-1;
    }

    public Helper getHelper(){
        SharedPreferences sharedPreferences = mcCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
        return new Helper(
                sharedPreferences.getInt("id",-1),
                sharedPreferences.getFloat("rating",0),
                sharedPreferences.getString("student_id",null),
                sharedPreferences.getString("name",null),
                sharedPreferences.getString("email",null),
                sharedPreferences.getString("phone",null),
                sharedPreferences.getString("gender",null),
                sharedPreferences.getString("category",null),
                sharedPreferences.getString("description",null)
        );
    }

    public Requestor getRequestor(){
        SharedPreferences sharedPreferences = mcCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
        return new Requestor(
                sharedPreferences.getInt("id",-1),
                sharedPreferences.getString("student_id",null),
                sharedPreferences.getString("name",null),
                sharedPreferences.getString("email",null),
                sharedPreferences.getString("phone",null),
                sharedPreferences.getString("gender",null)
                );
    }

    public void clear(){
        SharedPreferences sharedPreferences = mcCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor=sharedPreferences.edit();
        editor.clear();
        editor.apply();
    }
}

Вот моя функция входа в систему, сработала функция входа в систему, я могу проверить мои student_id и student_password, но менеджер общих преференций, похоже, не сохраняет данные ответа

package com.example.call_for_help.activities;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.example.call_for_help.R;
import com.example.call_for_help.api.RetrofitClient;
import com.example.call_for_help.helper_activities.HelperActivity;
import com.example.call_for_help.models.Helper;
import com.example.call_for_help.models.HelperResponse;
import com.example.call_for_help.models.RequestorResponse;
import com.example.call_for_help.storage.SharedPrefManager;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private EditText editTextStudentId;
    private EditText editTextStudentPassword;
    private Button buttonLogin;
    private TextView textViewSignUp;
    private RadioGroup radioGroupUserType;
    private RadioButton radioButtonHelper;
    private RadioButton radioButtonRequestor;
    private TextView textViewMessage;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editTextStudentId=findViewById(R.id.editTextStudentId);
        editTextStudentPassword=findViewById(R.id.editTextStudentPassword);
        buttonLogin=findViewById(R.id.buttonLogin);
        textViewSignUp=findViewById(R.id.textViewSignUp);
        radioButtonHelper=findViewById(R.id.radioButtonHelper);
        radioButtonRequestor=findViewById(R.id.radioButtonRequestor);
        radioGroupUserType=findViewById(R.id.radioGroupUserType);
        textViewMessage=findViewById(R.id.textViewMessage);

        buttonLogin.setOnClickListener(this);
        textViewSignUp.setOnClickListener(this);
        radioButtonHelper.setOnClickListener(this);
        radioButtonRequestor.setOnClickListener(this);
    }


    private void helperLogin(){
        String student_id=editTextStudentId.getText().toString().trim();
        String student_password=editTextStudentPassword.getText().toString().trim();

        if(student_id.isEmpty()){
            editTextStudentId.setError("Student ID is required");
            editTextStudentId.requestFocus();
            return;
        }

        if(student_password.isEmpty()){
            editTextStudentPassword.setError("Plese fill up your password");
            editTextStudentPassword.requestFocus();
            return;
        }

        if(student_password.length()<6){
            editTextStudentPassword.setError("Password length should be at least 6");
            editTextStudentPassword.requestFocus();
            return;
        }



        Call<HelperResponse> call=RetrofitClient
                .getInstance().getApi().helperLogin(student_id,student_password);
        call.enqueue(new Callback<HelperResponse>() {
            @Override
            public void onResponse(Call<HelperResponse> call, Response<HelperResponse> response) {
                HelperResponse helperResponse = response.body();
                if(!helperResponse.isError()){
                    SharedPrefManager.getIntance(MainActivity.this)
                            .savehelper(helperResponse.getHelper());

                    Intent intent=new Intent(MainActivity.this, HelperActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    startActivity(intent);

                }else{
                    Toast.makeText(MainActivity.this,"login failed",Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onFailure(Call<HelperResponse> call, Throwable t) {

            }
        });

    }

    private void requestorlogin(){
        String student_id=editTextStudentId.getText().toString().trim();
        String student_password=editTextStudentPassword.getText().toString().trim();

        if(student_id.isEmpty()){
            editTextStudentId.setError("Student ID is required");
            editTextStudentId.requestFocus();
            return;
        }

        if(student_password.isEmpty()){
            editTextStudentPassword.setError("Please fill up your password");
            editTextStudentPassword.requestFocus();
            return;
        }

        if(student_password.length()<6){
            editTextStudentPassword.setError("Password length should be at least 6");
            editTextStudentPassword.requestFocus();
            return;
        }

        Call<RequestorResponse> call=RetrofitClient
                .getInstance().getApi().requestorLogin(student_id,student_password);
        call.enqueue(new Callback<RequestorResponse>() {
            @Override
            public void onResponse(Call<RequestorResponse> call, Response<RequestorResponse> response) {
                RequestorResponse requestorResponse = response.body();
                if(!requestorResponse.isError()){
                    SharedPrefManager.getIntance(MainActivity.this)
                            .saverequestor(requestorResponse.getRequestor());

                    Intent intent=new Intent(MainActivity.this, HelperActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    startActivity(intent);
                }else{
                    Toast.makeText(MainActivity.this,"login failed",Toast.LENGTH_LONG).show();
                }

            }

            @Override
            public void onFailure(Call<RequestorResponse> call, Throwable t) {

            }
        });



    }
    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.buttonLogin:
            if(radioButtonHelper.isChecked()){
                helperLogin();
            }else if(radioButtonRequestor.isChecked()){
                requestorlogin();
            }else if(!radioButtonRequestor.isChecked() && !radioButtonHelper.isChecked()){
                Toast.makeText(this,"Please Select A User Type",Toast.LENGTH_SHORT).show();
            }
                break;
            case R.id.textViewSignUp:
                startActivity(new Intent(this,SignUpActivity.class));

        }
    }
}

Вот моя модель для менеджера с общими префами

package com.example.call_for_help.models;

public class Helper {
    private int helper_id;
    private float helper_rating;
    private String helper_student_id,helper_name,helper_email,helper_phone,helper_gender,helper_category,helper_description;

    public Helper(int helper_id, float helper_rating, String helper_student_id, String helper_name, String helper_email, String helper_phone, String helper_gender, String helper_category, String helper_description) {
        this.helper_id = helper_id;
        this.helper_rating = helper_rating;
        this.helper_student_id = helper_student_id;
        this.helper_name = helper_name;
        this.helper_email = helper_email;
        this.helper_phone = helper_phone;
        this.helper_gender = helper_gender;
        this.helper_category = helper_category;
        this.helper_description = helper_description;
    }

    public int getHelper_id() {
        return helper_id;
    }

    public float getHelper_rating() {
        return helper_rating;
    }

    public String getHelper_student_id() {
        return helper_student_id;
    }

    public String getHelper_name() {
        return helper_name;
    }

    public String getHelper_email() {
        return helper_email;
    }

    public String getHelper_phone() {
        return helper_phone;
    }

    public String getHelper_gender() {
        return helper_gender;
    }

    public String getHelper_category() {
        return helper_category;
    }

    public String getHelper_description() {
        return helper_description;
    }
}

Вот мой PHP

$app->post('/helperlogin',function(Request $request,Response $response){
    if(!haveEmptyParameters(array('student_id','student_password'),$request,$response)){
        $request_data = $request->getParsedBody();
        $student_id = $request_data['student_id'];
        $student_password = $request_data['student_password'];
        $db=new DbOperations;
        $result=$db->studentLogin($student_id,$student_password);
        if($result==USER_AUTHENTICATED){
            $helper=$db->getHelperByStudentId($student_id);
            $response_data=array();

            $response_data['error']=false;
            $response_data['message']='Login Succesful';
            $response_data['helper']=$helper;
            $response->write(json_encode($response_data));
            return $response
                        ->withHeader('Content-type', 'application/json')
                        ->withStatus(200); 
        }else if($result==USER_NOT_FOUND){
            $helper=$db->getHelperByStudentId($student_id);
            $response_data=array();

            $response_data['error']=true;
            $response_data['message']='Student not Exist';
            $response_data['helper']=$helper;
            $response->write(json_encode($response_data));
            return $response
                        ->withHeader('Content-type', 'application/json')
                        ->withStatus(404); 

        }else if($result==USER_PASSWORD_DO_NOT_MATCH){
            $helper=$db->getHelperByStudentId($student_id);
            $response_data=array();

            $response_data['error']=true;
            $response_data['message']='Invalid credential';
            $response_data['helper']=$helper;
            $response->write(json_encode($response_data));
            return $response
                        ->withHeader('Content-type', 'application/json')
                        ->withStatus(200); 

        }
    }

    return $response
                        ->withHeader('Content-type', 'application/json')
                        ->withStatus(422); 
});

public function getHelperByStudentId($student_id){
    $stmt=$this->con->prepare("SELECT helper.id,
    (SELECT AVG(rating.rating) FROM rating WHERE rating.helper_id=helper.id)as 'helper_rating',
    (SELECT student.student_id FROM student WHERE student.student_id=helper.student_id)as 'helper_student_id',
    (SELECT student.student_name FROM student WHERE student.student_id=helper.student_id)as 'helper_name',
    (SELECT student.student_email FROM student WHERE student.student_id=helper.student_id)as 'helper_email',
    (SELECT student.student_phone FROM student WHERE student.student_id=helper.student_id)as 'helper_phone',
    (SELECT student.student_gender FROM student WHERE student.student_id=helper.student_id)as 'helper_gender',
    helper.category,helper.description FROM helper WHERE helper.student_id=? ");
    $stmt->bind_param("s",$student_id);
    $stmt->execute();
    $stmt->bind_result($helper_id,$helper_rating,$helper_student_id,$helper_name,$helper_email,$helper_phone,$helper_gender,$helper_category,$helper_description);
    $stmt->fetch();
    $helper=array();
    $helper['helper_id']=$helper_id;
    $helper['helper_rating']=$helper_rating;
    $helper['helper_student_id']=$helper_student_id;
    $helper['helper_name']=$helper_name;
    $helper['helper_email']=$helper_email;
    $helper['helper_phone']=$helper_phone;
    $helper['helper_gender']=$helper_gender;
    $helper['helper_category']=$helper_category;
    $helper['helper_description']=$helper_description;
    return $helper;    
}
Здесь я звоню своему менеджеру общего доступа и где сообщение об ошибке указывает на

package com.example.call_for_help.fragments;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.example.call_for_help.R;
import com.example.call_for_help.storage.SharedPrefManager;

public class HelperProfileFragment extends Fragment {
    private TextView textViewHelperId,
            textViewHelperName,
            textViewHelperRating,
            textViewHelperemail,
            textViewHelperGender,textViewhelperPhone,textViewHelperCategory,textViewHelperDescription;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_helperhome,container,false);

    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        getActivity().setTitle("Helper Profile");
        textViewHelperId=view.findViewById(R.id.textViewHelperId);
        textViewHelperName=view.findViewById(R.id.textViewHelperName);
        textViewHelperRating=view.findViewById(R.id.textViewHelperRating);
        textViewHelperemail=view.findViewById(R.id.textViewHelperEmail);
        textViewhelperPhone=view.findViewById(R.id.textViewHelperPhone);
        textViewHelperGender=view.findViewById(R.id.textViewHelperGender);
        textViewHelperCategory=view.findViewById(R.id.textViewCategory);
        textViewHelperDescription=view.findViewById(R.id.textViewDescription);

        //float rating =SharedPrefManager.getIntance(getActivity()).getHelper().getHelper_rating();
        textViewHelperName.setText(SharedPrefManager.getIntance(getActivity()).getHelper().getHelper_name());



    }
}

Я очень новичок в Android Studio и PHP, хотя, мне потребовались часы, чтобы найти ошибку, но я все еще не могу ее найти.

1 Ответ

0 голосов
/ 26 февраля 2019

Пожалуйста, вставьте код файла макета фрагмента фрагмента "helperhome.xml ".1.) Убедитесь, что в этом xml-файле есть текстовое представление с идентификатором "textViewHelperName", поскольку вы используете его в следующей строке: textViewHelperName = view.findViewById (R.id.textViewHelperName);2.) Поскольку onViewCreated () вызывается после onCreateView (), пожалуйста, убедитесь, что textViewHelperName не используется перед onViewCreated (), так как до этого он будет нулевым.3.) Чтобы избежать исключения нулевого указателя, добавьте нулевую проверку.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...