cannot find symbol method getJSONArray(String) Volley - android

hi everyone i am working on a android project where i have to retrive the data form JSON. here is my link
I am trying to get the data using the below code
public class DisplayUser extends AppCompatActivity {
private TextView textViewResult;
private ProgressDialog loading;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_user);
textViewResult = (TextView) findViewById(R.id.check_data_id); // in this text view i will display the text
loading = ProgressDialog.show(this,"Please wait...","Fetching...",false,false);
String url = statics_demo.USER_URL+"7";// this is fixed url where i am getting the data
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.dismiss();
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(DisplayUser.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
JSONObject result;
private void showJSON(String response) {
try {
JSONArray obj = response.getJSONArray("responseMs");
for (int i = 0; i < obj.length(); i++) {
JSONObject jsonObject = obj.getJSONObject(i);
String name = jsonObject.getString("name");
System.out.println("luckyyyyyy"+name);
// String type = jsonObject.getString("type");
// retrieve the values like this so on..
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
}
When i run the code i am getting a erorr saying
"Error:(60, 37) error: cannot find symbol method getJSONArray(String)"

String s = "[]"; JsonParser parser = new JsonParser(); JsonElement tradeElement = parser.parse(s); JsonArray trade = tradeElement.getAsJsonArray();
you need to convert string to jsonarray first

Related

android studio - json to settext

<?php
$con = mysqli_connect("localhost", "database ", "data pass", "database name");
$userID = $_POST["userID"];
$result = mysqli_query($con, "SELECT * FROM USER WHERE userID like '$userID';");
$response = array();
while($row = mysqli_fetch_array($result)){
array_push($response, array("userPoint" => $row[4]));
}
echo json_encode(array("response" => $response));
mysqli_close($con);
?>
I'm trying to use this php to send userID data to my database and receive the point of the user and set the data to settext in android studio.
I used two class to obtain data from my database
public class GameRequest extends StringRequest {
final static private String URL = "http://smg6135.cafe24.com/ogi.php";
private Map<String, String> parameters;
public GameRequest(String userID, Response.Listener<String> listener){
super(Method.POST, URL, listener, null);
parameters = new HashMap<>();
parameters.put("userID", userID);
}
#Override
public Map<String, String> getParams(){
return parameters;
}
}
to send request to my php and
public class MainActivity extends AppCompatActivity {
private String userid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView idtext = (TextView) findViewById(R.id.userID);
final TextView point = (TextView) findViewById(R.id.point);
Intent intent = getIntent();
userid = intent.getStringExtra("userID");
idtext.setText(userid);
Response.Listener<String> responseLister = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
JSONObject jsonObject = new JSONObject(response);
String result = jsonObject.getString("userPoint");
JSONArray arr = new JSONArray(result);
point.setText(arr.toString());
}catch(Exception e){
e.printStackTrace();
}
}
};
GameRequest gameRequest = new GameRequest(userid, responseLister);
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
queue.add(gameRequest);
}
}
to receive the data in Json array and display it by textview. Somehow it doesn't work... can anyone help me with this problem?
You are receiving response in Array Object so use JSONArray instead of JSONObject as follows -
Response.Listener<String> responseLister = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("response");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonobject = jsonArray.getJSONObject(i);
String result = jsonobject.getString("userPoint");
point.setText(result);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
I hope its work for you. Thanks

How to Parse nested JSON using Volley?

MainClass.java
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
RecyclerView.Adapter adapter;
private Toolbar mToolbar;
private List<Onwardflights> onwardflights;
private static final String url = "http://tripofareapi.herokuapp.com/flightapi/src=DEL&dest=BOM&depdate=20180420&arrdate=20180422"; // https: url will insert here
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_flight_suggestion);
mToolbar = (Toolbar) findViewById(R.id.flight_suggestion_appbar);
Bundle bundle = getIntent().getExtras();
String from = bundle.getString("from");
String to = bundle.getString("to");
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle(from + "-" + to);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mToolbar.setTitleTextColor(Color.WHITE);
recyclerView = (RecyclerView) findViewById(R.id.flight_suggestion_recyclerview);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
onwardflights = new ArrayList<>();
getdata();
}
This is what i have done
private void getdata() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Please wait, while we load the data");
progressDialog.show();
//*Could not understand how to parse FARE objects*
StringRequest request = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jo = jsonArray.getJSONObject(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(request);
}
Try this.
private void getdata() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Please wait, while we load the data");
progressDialog.show();
//*Could not understand how to parse FARE objects*
StringRequest request = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
JSONObject data = jsonObject.getJSONObject("data");
JSONArray returnflights = data.getJSONArray("returnflights");
JSONArray onwardflights = data.getJSONArray("onwardflights");
for (int i = 0; i < returnflights.length(); i++) {
JSONObject returnFlightChild = returnflights.getJSONObject(i);
//returnFlights objects
}
for (int i = 0; i < onwardflights.length(); i++) {
JSONObject onwardFlightsChild = onwardflights.getJSONObject(i);
//onwardFlight objects
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(request);
}
First check your response format in Json formatter and validator.
Your json response has 2 json object
data
data_length
to get JSONObject form a Json user getJSONObject("key") and to get JSONArray from Json use getJSONArray("key").
As node data is a JSONObject use getJSONObject("key")` to get that.
JSONObject jsonObject = new JSONObject(response);
JSONObject data = jsonObject.getJSONObject("data");
JSONArray jsArray1 = data.getJSONArray("returnflights");
JSONArray jsArray2 = data.getJSONArray("onwardflights");
for (int i = 0; i < jsArray1.length(); i++) {
JSONObject jo = jsArray1.getJSONObject(i);
}
..................
Check this tutorial to learn how to parse Json

How to get data with this Json

I want to show data of below JSON:
{"success":true,"message":"","result":{"Bid":3924.01000000,"Ask":3925.00000000,"Last":3924.00000000}}
I am new in android and from all tutorials, I somehow access this data but I want to show only "Last" data figure but my code shows whole "result" string.
String firstname;
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView)findViewById(R.id.name);
new AsyncTaskParseJson().execute();
}
// you can make this class as another java file so it will be separated from your main activity.
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
final String TAG = "AsyncTaskParseJson.java";
// set your json string url here
String yourJsonStringUrl = "https://bittrex.com/api/v1.1/public/getticker?market=usdt-btc";
// contacts JSONArray
JSONArray dataJsonArr = null;
protected void onPreExecute() {}
protected String doInBackground(String... arg0) {
try {
// instantiate our json parser
JSONParser jParser = new JSONParser();
// get json string from url
JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);
firstname = json.getString("result");
Log.e(TAG, "Last: " + firstname);
}
catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String strFromDoInBg) {
tv.setText(""+firstname);
}
}
You are not making a network call. You are just parsing your Url. You need to make network call. You can use volley for this. In your onCreate method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView)findViewById(R.id.name);
RequestQueue queue = Volley.newRequestQueue(this);
String url ="https://bittrex.com/api/v1.1/public/getticker?market=usdt-btc";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject json = new JSONObject(response);
try {
JSONObject result = json.getJSONObject("result");
Double last = result.getDouble("Last");
tv.setText(String.valueOf(last));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
you need to define internet permission in Manifest.xml
<uses-permission android:name="android.permission.INTERNET" />
You need to include volley library for this http request. Include this in build.gradle of your app
dependencies {
.
.
compile 'com.android.volley:volley:1.0.0'
.
.
}
I think you should be able to do this
JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);
return "" + json.get("result").getDouble("Last");
The string is returned from doInBackground to onPostExecute in the strFromDoInBg variable, but if you prefer:
firstname = "" + json.get("result").getDouble("Last");
would also work

Android - Same JSON parsing class for different web services

I have made a JSONParse class for parsing JSON response. I have to call 3 web services. But I want to use only that SINGLE class for parsing JSON response for all 3 web services. All 3 web services has different keys and values. What I have done is like below..
MainActivity.java
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
// Anything Else Goes Here
private ArrayList<ModelCourse> ArrayListModelCourses;
// Variables
private String url = "stream.php";
private String career_path = "";
// Widgets
private ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
initialisation();
find_view_by_id();
clickListners();
fetchData();
}
private void initialisation() {
ArrayListModelCourses = new ArrayList<>();
}
private void find_view_by_id() {
lv = (ListView) findViewById(R.id.list_view);
}
private void clickListners() {
lv.setOnItemClickListener(this);
}
private void fetchData() {
StringRequest stringReq = new StringRequest(Request.Method.POST, Constants.base_url + url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jo = new JSONObject(response);
if (jo.has("success")) {
JsonParse jsonParse = new JsonParse(response);
ArrayListModelCourses = jsonParse.parseJson();
} else {
Toast.makeText(MainActivity.this, "Error msg from server!!", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
CustomAdapter ca = new CustomAdapter(getApplicationContext(), ArrayListModelCourses);
lv.setAdapter(ca);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Error:" + error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("user_id", "51");
return params;
}
};
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(stringReq);
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
String stream_name = ArrayListModelCourses.get(position).getmCourse_name();
String stream_id = ArrayListModelCourses.get(position).getmCourse_id();
career_path += stream_name + ", ";
fetchData();
}
}
JsonParse.java - The single class that I want to use for 3 web services.
public class JsonParse {
// Anything Else Goes Here
ArrayList<ModelCourse> modelCourses = new ArrayList<>();
// Variables
public static final String KEY_ARRAY = "stream_name";
public static final String KEY_ID = "stream_id";
public static final String KEY_NAME = "stream_name";
private String mJsonRes;
public JsonParse(String jsonRes) {
this.mJsonRes = jsonRes;
}
public ArrayList<ModelCourse> parseJson() throws JSONException {
JSONObject jo = new JSONObject(mJsonRes);
JSONArray ja = jo.getJSONArray(KEY_ARRAY);
for (int i = 0; i < ja.length(); i++) {
ModelCourse modelCourseObj = new ModelCourse();
JSONObject object = ja.getJSONObject(i);
modelCourseObj.mCourse_id = object.getString(KEY_ID);
modelCourseObj.mCourse_name = object.getString(KEY_NAME);
modelCourses.add(modelCourseObj);
}
return modelCourses;
}
}
Thanks in advance.
Use can use Gson for mapping json data to objects.
Create models classes for your json data. (use link http://www.jsonschema2pojo.org/)
Now in your MainActivity onResponse() method pass the string response to JsonParse class.
In JsonParse class parse your json data
Gson gson = new Gson();
gson.fromJson(jsonString, JsonModelRootClassName.class);
You can create one method to get "JsonModelRootClassName" based on your web services call.

Android Volley to parse JSON and put into listview is not working

I am using this guide here:
http://www.androidhive.info/2014/07/android-custom-listview-with-image-and-text-using-volley/
I put
System.out.println(error.getMessage());
in my code below and here were the errors it was showing me:
01-13 18:53:21.425 1915-1915/com.app.dev.myapplication I/System.out: org.json.JSONException: Value {"server_response":[{"first_name":"bob","last_name":"john","user_name":"bobthebuilder","avatar":"stringOfURL"}]} of type org.json.JSONObject cannot be converted to JSONArray
01-13 18:53:21.425 1915-1915/com.app.dev.myapplication D/Volley: [1] 2.onErrorResponse: SearchActivity
Here is my JSON Code:
{"server_response":[{"first_name":"bob","last_name":"john","user_name":"bobthebuilder","avatar":"stringOfURL"}]}
Here is my code:
public class SearchActivity extends AppCompatActivity {
String JSON_STRING,sq,js_username,js_first_name,js_last_name,js_avatar;
EditText et_sq;
private static final String json_user_search_url = "http://www.domain.com/string.php";
private static final String TAG = SearchActivity.class.getSimpleName();
private List<SearchResults> movieList = new ArrayList<SearchResults>();
private ListView listView;
private CustomListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
listView = (ListView) findViewById(R.id.listViewSearch);
adapter = new CustomListAdapter(this, movieList);
listView.setAdapter(adapter);
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(json_user_search_url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONArray responseArray = response.getJSONArray("server_response");
JSONObject content = responseArray.getJSONObject(0);
SearchResults movie = new SearchResults();
movie.setUser_name(obj.getString("user_name"));
movie.setFirst_name(obj.getString("first_name"));
movie.setLast_name(obj.getString("last_name"));
movie.setAvatarUrl(obj.getString("avatar"));
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println(error.getMessage());
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
}
The response is a JSON object with "server_response" being it's only value. "server_response" itself is a JSONArray wrapped by a JSONObject, so you need to change:
new JsonArrayRequest(json_user_search_url, new Response.Listener<JSONArray>() {
to:
new JsonObjectRequest(json_user_search_url, new Response.Listener<JSONObject>() {
as well as overriding onResponse:
#Override
public void onResponse(JSONObject response) {
And then you can access the response and get the "server_response" without looping through the contents like you are:
#Override
public void onResponse(JSONObject response) {
JSONArray responseArray = response.getJSONArray("server_response");
JSONObject content = responseArray.getJSONObject(0);
String firstName = content.getString("first_name");
//get rest of the objects similarly...
}
EDIT: Made a mistake in the original answer. "server_response" is a JSONArray containing a JSON object at index 0. You access the JSONObject and store it's content an object, then extract the key/value pairs for it's data.

Categories

Resources