Mohammadreza Mohammadreza - 3 months ago 67
Android Question

Android Volley error while fetch JSON data

I have a JSON file in my localhost and I'm trying to fetch all it's data on my android application using Volley Requests.
Now, while I try to fetch my Parsed data (using JSON) I got some unknown errors! I'm using my emulator to test my application.

here is my JSON File:

{"dolaaye_posts":[{"id":"1","post_subject":"salam","post_desc":"salam"},{"id":"2","post_subject":"????","post_desc":"????"}],"success":1}


here is my MainActivity.java:

package ir.dolaaye;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import com.android.volley.AuthFailureError;
import com.android.volley.Cache;
import com.android.volley.NetworkError;
import com.android.volley.NoConnectionError;
import com.android.volley.ParseError;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;

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

import java.io.UnsupportedEncodingException;

public class MainActivity extends AppCompatActivity {

/**
* The {@link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {@link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {@link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;

/**
* The {@link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);


////////start of Volley Request///////////////



String tag_json_array = "tag_json_array";
/**
* @url = Url for get json Object
*/
String url = "http://10.0.2.2:1378/scripts/dolaaye/posts.json";
/**
* Show Progress Dialog
* Before Get Data From Server
* Or
* Get Error From Server
*/
final ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("در حال جمع آوری اطلاعات...");
pDialog.show();

/**
* Create Request For Get Json Array From Server
*
* Exist To Method In The Request :
* 1 : onResponse => That Get Response For Server
* If Data Exist In The Server
*
* 2 : onErrorResponse => That Show Error
* If Data Do Not Exist In The Server
*/
JsonArrayRequest jsonArrReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray jsonArray) {
Log.e("LOG", jsonArray.toString());
for (int i = 0 ; i < jsonArray.length() ; i++)
{
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Log.i("LOG", "object : " + jsonObject.getString("id"));
} catch (JSONException e) {
e.printStackTrace();
}
}
pDialog.hide();
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
VolleyLog.e("VolleyError", volleyError.getMessage());

if (volleyError instanceof TimeoutError || volleyError instanceof NoConnectionError) {
VolleyLog.e("VolleyError", volleyError.getMessage());
} else if (volleyError instanceof AuthFailureError) {
//TODO
} else if (volleyError instanceof ServerError) {
//TODO
} else if (volleyError instanceof NetworkError) {
//TODO
} else if (volleyError instanceof ParseError) {
//TODO
}
pDialog.hide();
}
});

Cache cache = G.getInstance().getRequestQueue().getCache();
Cache.Entry entry = cache.get(url);
if (entry != null){
try {
String data = new String(entry.data, "UTF-8");
Log.i("LOG",data);
pDialog.hide();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
}
G.getInstance().addToRequestQueue(jsonArrReq,tag_json_array);


////end of Volley Request //////////////////////////////////

}
}


I have set INTERNET-PERMISSION and ACCESS_NETWORK_STATE to my manifest. here is my logcat:

08-23 13:33:49.767 22388-22388/ir.dolaaye E/Volley: [1] 2.onErrorResponse: VolleyError


I don't know why!

Answer

you are getting a jsonObject in responce but you are handling JsonArray in your code by using JsonArrayRequest , so you have to JsonObject Request as following

JsonObjectRequest jsObjRequest = new JsonObjectRequest (Request.Method.GET, url, null, new Response.Listener() {

@Override
public void onResponse(JSONObject response) {
    mTxtDisplay.setText("Response: " + response.toString());
}

}, new Response.ErrorListener() {

@Override
public void onErrorResponse(VolleyError error) {
    // TODO Auto-generated method stub

}

});

for more info follow the android developer link

https://developer.android.com/training/volley/request.html