Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Volley request is not working

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>
like image 305
Shivam Avatar asked Sep 15 '15 05:09

Shivam


People also ask

How Volley works in Android?

It manages the processing and caching of network requests and it saves developers valuable time from writing the same network call/cache code again and again. Volley is not suitable for large download or streaming operations since Volley holds all responses in memory during parsing.

How to use Volley in Android java?

Android App Development for Beginners This example demonstrate about How to use simple volley request in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.

How to get Volley in Android Studio?

Understanding RequestQueue & Working With Volley In Android: To use it, first you need to instantiate the RequestQueue and later on you can start or stop request, add or cancel request and access the response cache(s). RequestQueue queue = Volley. newRequestQueue(this);


1 Answers

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.

like image 153
AndiGeeky Avatar answered Sep 29 '22 19:09

AndiGeeky