Android: Volley request is not working
Asked Answered
S

6

6

I am new to android and volley. I created one login program to fetch json data from my server but it is not working. It is not showing the json response after clicking the login button. I am pasting my code below.

MainActivity.java

package com.volley.cuser.volleyexample;

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

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

public class MainActivity extends Activity {

    private TextView txtDisplay;
    EditText editText;
    EditText editText2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editText = (EditText) findViewById(R.id.username);
        editText2 = (EditText) findViewById(R.id.password);
    }

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

    public void studentLogin(View view) {
        String username = editText.getText().toString();
        String password = editText2.getText().toString();
        RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
        String url = "http://afterklass.in/api/";
        JSONObject js = new JSONObject();
        try {
            JSONObject jsonobject = new JSONObject();

            jsonobject.put("email_mobile", username);
            jsonobject.put("passwd", password);
            jsonobject.put("m", "student");
            jsonobject.put("uc", "signin");
            jsonobject.put("signin", "Sign+In");

            js.put("data", jsonobject.toString());

        }catch (JSONException e) {
            e.printStackTrace();
        }
        JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST, url, js, new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                // TODO Auto-generated method stub
                txtDisplay.setText("Response => " + response.toString());
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                //String json = null;

                //NetworkResponse response = error.networkResponse;
                //if(response != null && response.data != null){
                    //switch(response.statusCode){
                        //case 400:
                            //txtDisplay.setText("Error => " + response.data);
                            //break;
                    //}
                    //txtDisplay.setText("Error => " + response.statusCode);
                    //Additional cases
                //}
                Log.d("ERROR", error.toString());
            }
        });

        queue.add(jsObjRequest);
    }

}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <EditText android:id="@+id/username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/username" />
    <EditText android:id="@+id/password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/password" />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/login"
        android:onClick="studentLogin" />

</LinearLayout>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.volley.cuser.volleyexample" >

    <uses-permission android:name="android.permission.INTERNET"/>'

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
Standridge answered 15/9, 2015 at 5:32 Comment(21)
What is the error message???Mingle
I am not getting any error messageStandridge
@Shivam: It is not redirecting to the other page where is code for starting new Activity?Composer
I thought it will show on the same page. No need of another activity. Because i tried with google api that was showing json response in same page only.Standridge
In your question you have written you are getting error message.Mingle
Sorry for that i will edit that but main problem is that json response is not coming after clicking the login button.Standridge
from where do you calling your studentLogin(view); method.?Sulk
I am using it on click of login button.Standridge
but in that method you are initializing everytime your edittext first and then getting text from it so it would return null data.Sulk
@MaheshB So you mean to say String username and String password is null?Standridge
Try debugging to see if onErrorResponse or onResponse called.Sympathetic
@Sympathetic I am not able to understand. what do you mean?Standridge
@Standridge : Mai know what is this webservice call is about "assign.afterclass.co.in/apicheck"; ?? Like its signin request ..??Olivarez
@MamataGelanee Yes it is a signin request which will give some data in json response.Standridge
@ Shivam : Can i access that url and make request ..??Olivarez
@MamataGelanee yaa sure.Standridge
@MamataGelanee I got it. These parameters are going as jsonobject and in webservice it is handling as normal post parameters. Can we send normal post parameters with JsonObjectRequest? Thanks for all your efforts.Standridge
@Standridge : yeah obviously..!!Olivarez
@Standridge : Please check my answer -> #32578907Olivarez
@MamataGelanee I upvoted your answer. After checking it with my code I will mark it as correct. ThanksStandridge
@Standridge : Welcome..!!Olivarez
O
4

Please change your jsonRequest to StringRequest and add custom header to it :

Edited :

private static final String TAG = YourActivity.class.getSimpleName();
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                // Display the first 500 characters of the response string.
                Log.e(TAG, "Successfully signed in : " + response.toString());
            }
        }, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        Log.e(TAG, "Error at sign in : " + error.getMessage());
    }
}) {
    @Override
    public HashMap<String, String> getParams() {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("email_mobile", username);
        params.put("passwd", password);
        params.put("m", "student");
        params.put("uc", "signin");
        params.put("signin", "Sign+In");
        return params;
    }
};

Thanks.

Olivarez answered 15/9, 2015 at 8:9 Comment(2)
Thanks for help Mamata, my program is working now. Hope I can get some more help from you. :)Standridge
can anybody help me on this question ? #34367935Trampoline
D
3

In android manifest line:

<uses-permission android:name="android.permission.INTERNET"/>'

remove that ' on end of the line

Disencumber answered 13/2, 2018 at 16:50 Comment(0)
M
2

Instead of the below line:

 RequestQueue queue = Volley.newRequestQueue(this);

Change it to like this:

RequestQueue queue = Volley.newRequestQueue(MainActivity.this);

And declare you EditText in onCreate method like as follows:

EditText editText;
EditText editText2;

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editText = (EditText) findViewById(R.id.username);
        editText2 = (EditText) findViewById(R.id.password);
  }
Mingle answered 15/9, 2015 at 5:55 Comment(8)
Check in your public void onErrorResponse(VolleyError error) method whether you are getting any Error or not.Mingle
public void onErrorResponse(VolleyError error) { String json = null; NetworkResponse response = error.networkResponse; if(response != null && response.data != null){ switch(response.statusCode){ case 400: txtDisplay.setText("Error => " + response.data); break; } txtDisplay.setText("Error => " + response.statusCode); //Additional cases } }Standridge
I am checking like this. Is it fine?Standridge
Just print log **Log.d("ERROR",error.toString()); and comment the other code for now.Mingle
09-15 11:44:40.428 3282-3282/com.volley.cuser.volleyexample D/ERROR﹕ com.android.volley.ParseError: org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObjectStandridge
Intead of JsonObjectRequest try StringRequestMingle
Let us continue this discussion in chat.Standridge
I got it. These parameters are going as jsonobject and in webservice it is handling as normal post parameters. Can we send normal post parameters with JsonObjectRequest? Thanks for all your efforts.Standridge
B
1

When you are sending JSON data, set conent type like this... hope this may help

    @Override
    public Map<String, String> getHeaders ()
    throws AuthFailureError {
        Map<String, String> params = new HashMap<String,
                String>();
        params.put("Content-Type", "application/json");
        return params;
    }
Beaston answered 15/9, 2015 at 6:3 Comment(8)
No I don't know how to check. I am new to it. please help.Standridge
System.out.println("Any message") after every statement.. and check where it stucks (means where execution stops and it is not printing your message)..Sulk
09-15 11:44:40.428 3282-3282/com.volley.cuser.volleyexample D/ERROR﹕ com.android.volley.ParseError: org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObjectStandridge
hmm seems like the webservice is not properly written..... its not android side error buddy.... check the webservice again for proper output..Sulk
But this api is working fine for other people and they are using it. Maybe my approach is not correct.Standridge
I got it. These parameters are going as jsonobject and in webservice it is handling as normal post parameters. Can we send normal post parameters with JsonObjectRequest? Thanks for all your efforts.Standridge
yes... as like getHeaders() method there is also a getParams(); method in which you can send your parameters in HashMap<String, Strring>();Sulk
Can we do anything on android side to handle it. beacause I cant change those apis.Standridge
G
0

add following to your build.gradle file

compile 'com.mcxiaoke.volley:library:1.0.19'

Graphic answered 20/5, 2017 at 3:58 Comment(0)
C
0

You can also do this :

    HashMap<String, String> params = new HashMap<String, String>();
    params.put("email_mobile", username);
    params.put("passwd", password);

    JSONObject parameters = new JSONObject(params);

    JsonObjectRequest newRequest = new JsonObjectRequest(Request.Method.POST, URL, parametres, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {

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

        }
    });

Here we are passing the object to the constructor to get the proper response.

Carve answered 12/7, 2018 at 5:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.