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>
Shivam
  • 702
  • 2
  • 10
  • 25

6 Answers6

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.

Partharaj Deb
  • 864
  • 1
  • 8
  • 22
AndiGeeky
  • 11,266
  • 6
  • 50
  • 66
  • Thanks for help Mamata, my program is working now. Hope I can get some more help from you. :) – Shivam Sep 18 '15 at 09:32
  • can anybody help me on this question ? http://stackoverflow.com/questions/34367435/volley-getting-a-error-response-in-5-1-1-but-working-perfectly-in-android-4 – Abhigyan Dec 21 '15 at 07:51
3

In android manifest line:

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

remove that ' on end of the line

Rajko
  • 31
  • 1
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);
  }
Pankaj
  • 7,908
  • 6
  • 42
  • 65
  • Check in your **public void onErrorResponse(VolleyError error)** method whether you are getting any **Error** or not. – Pankaj Sep 15 '15 at 06:02
  • 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 } } – Shivam Sep 15 '15 at 06:08
  • I am checking like this. Is it fine? – Shivam Sep 15 '15 at 06:09
  • Just print log **Log.d("ERROR",error.toString()); and comment the other code for now. – Pankaj Sep 15 '15 at 06:11
  • 09-15 11:44:40.428 3282-3282/com.volley.cuser.volleyexample D/ERROR﹕ com.android.volley.ParseError: org.json.JSONException: Value – Shivam Sep 15 '15 at 06:15
  • Intead of **JsonObjectRequest** try **StringRequest** – Pankaj Sep 15 '15 at 06:22
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/89639/discussion-between-shivam-and-clairvoyant). – Shivam Sep 15 '15 at 06:25
  • 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. – Shivam Sep 15 '15 at 06:51
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;
    }
Mahesh B ツ
  • 128
  • 4
  • 14
  • No I don't know how to check. I am new to it. please help. – Shivam Sep 15 '15 at 06:11
  • System.out.println("Any message") after every statement.. and check where it stucks (means where execution stops and it is not printing your message).. – Mahesh B ツ Sep 15 '15 at 06:13
  • 09-15 11:44:40.428 3282-3282/com.volley.cuser.volleyexample D/ERROR﹕ com.android.volley.ParseError: org.json.JSONException: Value – Shivam Sep 15 '15 at 06:17
  • hmm seems like the webservice is not properly written..... its not android side error buddy.... check the webservice again for proper output.. – Mahesh B ツ Sep 15 '15 at 06:19
  • But this api is working fine for other people and they are using it. Maybe my approach is not correct. – Shivam Sep 15 '15 at 06:23
  • 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. – Shivam Sep 15 '15 at 06:51
  • yes... as like getHeaders() method there is also a getParams(); method in which you can send your parameters in HashMap(); – Mahesh B ツ Sep 15 '15 at 06:58
  • Can we do anything on android side to handle it. beacause I cant change those apis. – Shivam Sep 15 '15 at 07:00
0

add following to your build.gradle file

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

Waruna Manjula
  • 3,067
  • 1
  • 34
  • 33
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.

Abhishek Sengupta
  • 2,938
  • 1
  • 28
  • 35