Android:如何使用** Volley **

时间:2018-11-23 08:04:27

标签: java android android-volley

登录和注册的过程是 Volley 。当用户成功执行任何操作并希望看到我声明为不可见的 log_out 菜单项时,我想删除登录和注册选项。有什么方法可以使此应用程序中的所有导航抽屉中的登录和注册信息不可见?

此活动以 jsonObject形式

获得成功的响应

LogIn.java

 public class LogIn extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

// declare the variables

private EditText email ,password;
private Button btn_login;
private ProgressBar loading;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_log_in2);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    // setting variables

    loading = findViewById(R.id.loading);
    email = findViewById(R.id.email);
    password = findViewById(R.id.password);
    btn_login = findViewById(R.id.btn_login);
    //btn_log_out = findViewById(R.id.log_out);
    TextView link_register = findViewById(R.id.link_regist);




    // click listenr for logging a user

    btn_login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String mEmail = email.getText().toString().trim();
            String mPass = password.getText().toString().trim();

            if(!mEmail.isEmpty() || !mPass.isEmpty()){
                LogIn(mEmail, mPass);
            }else {
                email.setError("Please insert an e-mail");
                password.setError("Please insert a password");
            }
        }
    });

    link_register.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(LogIn.this,Registration.class));
        }
    });

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);


}



private void LogIn(final String email, final String password) {

    loading.setVisibility(View.VISIBLE);
    btn_login.setVisibility(View.GONE);

    String URL_LOGIN = "https://maknam.com/Portal2/apis/login.php";
    StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_LOGIN,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {

                        JSONObject jsonObject = new JSONObject(response);
                        String success = jsonObject.getString("success");
                        JSONArray jsonArray = jsonObject.getJSONArray("login");

                        if (success.equals("1")) {
                            for (int i = 0; i < jsonArray.length(); i++)
                            {

                                JSONObject object = jsonArray.getJSONObject(i);

                                //noinspection unused
                                String name = object.getString("name").trim();
                                //noinspection unused,unused
                                String email = object.getString("email").trim();

                                Intent lg = new Intent(LogIn.this,
                                        Home.class);
                                startActivity(lg);

                                loading.setVisibility(View.GONE);
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        loading.setVisibility(View.GONE);
                        btn_login.setVisibility(View.VISIBLE);
                        Toast.makeText(LogIn.this, "Error"+ e.toString(), Toast.LENGTH_SHORT).show();

                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                    loading.setVisibility(View.GONE);
                    btn_login.setVisibility(View.VISIBLE);
                    Toast.makeText(LogIn.this, "Error"+ error.toString(), Toast.LENGTH_SHORT).show();
                }
            }
    )


    {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<>();
            params.put("email", email);
            params.put("password", password);
            return params;

        }
    };

    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);




}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.log_in, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

此活动还注册在显示错误 jsonObject 中,或 成功事件

Registration.Java

   public class Registration extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

// declare variables
private EditText name;
private EditText email;
private EditText password;
private Button btn_register;
private ProgressBar loading;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_registration);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);


    loading = findViewById(R.id.loading);
    name = findViewById(R.id.name);
    email = findViewById(R.id.email);
    password = findViewById(R.id.password);
    EditText c_password = findViewById(R.id.c_password);
    btn_register = findViewById(R.id.btn_register);
    // click view for register a new user

    btn_register.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Register();
        }
    });

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
}


private void Register(){
    loading.setVisibility(View.VISIBLE);
    btn_register.setVisibility(View.GONE);



    final String name = this.name.getText().toString().trim();
    final String email = this.email.getText().toString().trim();
    final String password = this.password.getText().toString().trim();

    String URL_REGST = "http://maknam.com/Portal2/apis/register.php";
    //String URL_REGST = "http://192.168.1.103/android_register_login/register.php";
    StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_REGST, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            try {
                JSONObject jsonObject = new JSONObject(response);
                String success = jsonObject.getString("success");
                if (success.equals("1")) {

                    Toast.makeText(Registration.this, "Registration Successful!", Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
                Toast.makeText(Registration.this, "Registration Error" + e.toString(), Toast.LENGTH_SHORT).show();
                loading.setVisibility(View.GONE);
                btn_register.setVisibility(View.VISIBLE);
            }
        }
    },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                    Toast.makeText(Registration.this, "Registration Error" + error.toString(), Toast.LENGTH_SHORT).show();
                    loading.setVisibility(View.GONE);
                    btn_register.setVisibility(View.VISIBLE);

                }
            })

    {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {

            Map<String, String> params = new HashMap<>();
            params.put("name",name);
            params.put("email", email);
            params.put("password", password);
            return params;

        }
    };

    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);

}

@Override
public void onBackPressed() {
   //functionality for backpress
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.registration, menu);
    return true;
}

注销菜单默认为不可见

activity_login.drawer

 <group android:checkableBehavior="single">
    <item

        android:id="@+id/nav_products"
        android:icon="@drawable/ic_shopping_cart_black_24px_product"
        android:title="Products"
        tools:ignore="HardcodedText" />
    <item
        android:id="@+id/verify_product"
        android:icon="@drawable/ic_search_black_48dp"
        android:title="Verify A Product"
        tools:ignore="HardcodedText" />

    <item android:id="@+id/log_in"
        android:icon="@drawable/ic_account_box_black_48dp"
        android:title="Log In"
        tools:ignore="HardcodedText"/>

    <item
        android:id="@+id/register"
        android:icon="@drawable/reg_black_48dp"
        android:title="Sign Up"
        tools:ignore="HardcodedText"/>

    <item
        android:id="@+id/recent_verified"
        android:icon="@drawable/ic_history_black_48dp"
        android:title="History"
        tools:ignore="HardcodedText" />


    <item
        android:id="@+id/discussion"
        android:icon="@drawable/ic_forum_black_48dp"
        android:title="Ulema's Discussion"
        tools:ignore="HardcodedText" />

    <item
        android:id="@+id/notifications"
        android:icon="@drawable/ic_notifications_black_48dp"
        android:title="Notifications"
        tools:ignore="HardcodedText" />

    <item
        android:id="@+id/contact_us"
        android:icon="@drawable/ic_contacts_black_48dp"
        android:title="Contact Us"
        tools:ignore="HardcodedText" />


    <item
        android:id="@+id/settings"
        android:icon="@drawable/ic_settings_black_48dp"
        android:title="Settings"
        tools:ignore="HardcodedText" />
    <item
        android:id="@+id/report_problem"
        android:icon="@drawable/ic_report_black_48dp"
        android:title="Report A Problem"
        tools:ignore="HardcodedText" />

    <item
        android:id="@+id/log_out"
        android:icon="@drawable/product_5"
        android:title="@string/logout"
        android:visible="false" />
</group>

activity_registration.drawer

same as acitvity_login.drawer

1 个答案:

答案 0 :(得分:0)

尝试此代码

private Menu menu;

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    this.menu = menu;
    getMenuInflater().inflate(R.menu.menu_layout, menu);
    return true;
}

private void toogleVisiblityOfMenuItem(boolean isVisible, int itemId){
    menu.findItem(itemId).setVisible(isVisible);
}