android studio - json to settext - android

<?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

Related

How to make the spinner selection value is based on the previous selected value?

I have a spinner on activity a, the spinner values is taken from a table inside database. When a user select the value from the spinner the value will be saved into same database but different table.
Then there is a button to next activity, on the next activity there is another spinner but I need the spinner selection value to display what I have selected on previous activity.
Android Code:
String text;
String url = "http:///10.92.5.51/test/get.php";
String spinURL = "http://10.92.5.51/test/getSpin.php";
private JSONArray result;
private ArrayList<String> districts;
private ArrayList<Integer> position;
Spinner spinex;
TextView spintext;
Button uploadBtn;
Integer r;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
districts = new ArrayList<String>();
spinex = (Spinner) findViewById(R.id.spiner);
spintext = findViewById(R.id.spinText);
uploadBtn = findViewById(R.id.btnUpload);
getData();
spinex.post(new Runnable() {
#Override
public void run() {
spinex.setSelection(4);
}
});
getPosition();
}
private void getData() {
StringRequest stringRequest = new StringRequest(url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
result = j.getJSONArray("result");
getDistrict(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating a request queue
MySingleton.getInstance(this).addToRequestQueue(stringRequest);
}
private void getPosition() {
StringRequest stringRequest = new StringRequest(spinURL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
result = j.getJSONArray("result");
getSpinPosition(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating a request queue
MySingleton.getInstance(this).addToRequestQueue(stringRequest);
}
private void getDistrict(JSONArray j) {
//Traversing through all the items in the json array
for (int i = 0; i < j.length(); i++) {
try {
//Getting json object
JSONObject json = j.getJSONObject(i);
//Adding the name of the student to array list
districts.add(json.getString("city_name"));
} catch (JSONException e) {
e.printStackTrace();
}
}
spinex.setAdapter(new ArrayAdapter<String>(Main2Activity.this, android.R.layout.simple_spinner_dropdown_item, districts));
}
private void getSpinPosition(JSONArray j) {
//Traversing through all the items in the json array
try {
//Getting json object
JSONObject json = j.getJSONObject(1);
//Adding the name of the student to array list
r = Integer.valueOf(json.getString("city_id"));
} catch (JSONException e) {
e.printStackTrace();
}
}
Here is the php code:
<?php
require_once('DBConnect.php');
$sql = "select * from city ORDER BY city_id ASC";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array(
'city_id'=>$row['city_id'],
'city_name'=>$row['city_name'],
)
);
}
echo json_encode(array("result"=>$result));
mysqli_close($con);

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

cannot find symbol method getJSONArray(String) Volley

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

json data without array name

This is my array which I retrieve from a url
[{"ash_id":"1","asg_code":"1226","ash_name":"hello","ash_cell":"123","ash_nic":"123","ash_long":"34.015","ash_lat":"71.5805","zm_id":null,"created_by":"0","created_date":"0000-00-00
00:00:00","last_updated":"2016-08-29 07:52:35"}]
I have array without array name, I can read data if there is name of jason array but I am unable to do that with this type of array.
any suggestion my code for json with array name
String json = serviceClient.makeServiceCall(URL_ITEMS, ServiceHandler.GET);
// print the json response in the log
Log.d("Get match fixture resps", "> " + json);
if (json != null) {
try {
Log.d("try", "in the try");
JSONObject jsonObj = new JSONObject(json);
Log.d("jsonObject", "new json Object");
// Getting JSON Array node
matchFixture = jsonObj.getJSONArray(TAG_FIXTURE);
Log.d("json aray", "user point array");
int len = matchFixture.length();
Log.d("len", "get array length");
for (int i = 0; i < matchFixture.length(); i++) {
JSONObject c = matchFixture.getJSONObject(i);
Double matchId = Double.parseDouble(c.getString(TAG_MATCHID));
Log.d("matchId", String.valueOf(matchId));
Double teamA = Double.valueOf(c.getString(TAG_TEAMA));
Log.d("teamA", String.valueOf(teamA));
String teamB = c.getString(TAG_TEAMB);
Log.d("teamB", teamB);`
List<Double> listMatch = new ArrayList<Double>();
List<Double> listA = new ArrayList<Double>();
List<String> listB = new ArrayList<String>();
Create three arrayList and add data in that list
if(json!=null)
{
try {
Log.d("try", "in the try");
JSONArray jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
listMatch.add(Double.parseDouble(c.getString(TAG_MATCHID)));
Log.d("matchId", String.valueOf(matchId));
listA.add(Double.valueOf(c.getString(TAG_TEAMA));
Log.d("teamA", String.valueOf(teamA));
listB.add(c.getString(TAG_TEAMB);
Log.d("teamB", teamB);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
directly pass jsonarray string to JSONArray object constructor.
String json = [{"ash_id":"1","asg_code":"1226","ash_name":"hello","ash_cell":"123","ash_nic":"123","ash_long":"34.015","ash_lat":"71.5805","zm_id":null,"created_by":"0","created_date":"0000-00-00 00:00:00","last_updated":"2016-08-29 07:52:35"}];
JSONArray array = new JSONArray(json);
You can directly pass the JSON response from the URL to the json if it is dynamic. Use something like this:
JSONArray jsonarray = new JSONArray(jsonStr);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String id = jsonobject.getString("ash_id");
String code = jsonobject.getString("ash_code");
String name = jsonobject.getString("ash_name");
String cell = jsonobject.getString("ash_cell");
String nic = jsonobject.getString("ash_nic");
String lng = jsonobject.getString("ash_long");
String lat = jsonobject.getString("ash_lat");
String zm_id = jsonobject.getString("zm_id");
String created_by = jsonobject.getString("created_by");
String created_date = jsonobject.getString("created_date");
String updated_date = jsonobject.getString("last_updated");
}
This will update your data, as long as the node names remain the same.
That's all :)
This code worked for me:
public class MainActivity extends AppCompatActivity {
private TextView textView;
private RequestQueue queue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text_view_result);
Button buttonParse = findViewById(R.id.button_parse);
queue = Volley.newRequestQueue(this);
buttonParse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
jsonParse();
}
});
}
private void jsonParse() {
String url = "http://10.216.70.19:8080/restServices/webapi/services/getAGVStatusList"; //This is my Json url
StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//weatherData.setText("Response is :- ");
parseData(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
textView.setText("Data Not Received");
}
});
queue.add(request);
super.onStart();
}
private void parseData(String response) {
try {
// Create JSOn Object
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i <jsonArray.length() ; i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
textView.setText(jsonObject.getString("batteryLevel")); //get the desired information from the Json object
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}

I am getting Error like below in android using volley.error is , org.json.JSONException: Index 3 out of range [0..3)

I am using volley library to achive network operation when i try to ru the program using below program i am gettin warning and getting size less than what i have in the url the warning message is org.json.JSONException: Index 3 out of range [0..3).
public class MainActivity extends AppCompatActivity {
TextView results;
String JsonURL = "http://184.73.181.186/jsondata.php";
String data = "";
RequestQueue requestQueue;
MyCustomBaseAdapter myCustomBaseAdapter;
ArrayList<StudentInfo> studentInfoList = new ArrayList<StudentInfo>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
requestQueue = Volley.newRequestQueue(this);
results = (TextView) findViewById(R.id.jsonData);
JsonArrayRequest arrayreq = new JsonArrayRequest(JsonURL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for(int i=0;i<lenghthofarray;i++){
JSONObject jresponse = response.getJSONObject(i);
final int numberOfItemsInResp = jresponse.length();
StudentInfo studentInfo = new StudentInfo();
String fname = jresponse.getString("fName");
String lName = jresponse.getString("lName");
String rollNo = jresponse.getString("rollNo");
String profilePic = jresponse.getString("profilePic");
studentInfo.setFname(fname);
studentInfo.setLname(lName);
studentInfo.setRoolNo(rollNo);
studentInfo.setStudpic(profilePic);
studentInfoList.add(studentInfo);
list.add(profilePic);
myCustomBaseAdapter = new MyCustomBaseAdapter(getApplicationContext(),studentInfoList);
JSONObject colorObj = response.getJSONObject(0);
JSONArray colorArry = colorObj.getJSONArray("marks");
for (int ii = 0; ii < colorArry.length(); ii++) {
JSONObject jsonObject = colorArry.getJSONObject(i);
String subjectName, marks;
subjectName = jsonObject.getString("subjectName");
marks = jsonObject.getString("marks");
}
data += "\nfName " + fname +
"\nHex Value : " + lName + "\n\n\n"+rollNo+"\n"+profilePic+"\n";
}
results.setText(data);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
// Handles errors that occur due to Volley
public void onErrorResponse(VolleyError error) {
Log.e("Volley", "Error");
}
}
);
}
}
The problem is in(i),replace i with ii
JSONObject jsonObject = colorArry.getJSONObject(i);
solved one
JSONObject jsonObject = colorArry.getJSONObject(ii);

Categories

Resources