Newbie here, i'm working on a simple app that display list of place based on api data for my assignment.
I'm planning to make a simple recyclerview that display preview image, place name, and place rating.
Here is the json that contain array of object
[
{
"xid":"N2180835380",
"name":"Stasiun Waytuba",
"rate":3,
"osm":"node/2180835380",
"wikidata":"Q19741325",
"kinds":"industrial_facilities,railway_stations,interesting_places",
"point":{
"lon":104.411728,
"lat":-4.379512
}
},
{
"xid":"N5374585862",
"name":"Stasiun Martapura",
"rate":3,
"osm":"node/5374585862",
"wikidata":"Q19741099",
"kinds":"other,unclassified_objects,interesting_places,tourist_object",
"point":{
"lon":104.346565,
"lat":-4.316566
}
},
{
...
}
]
But, the image url doesn't exist on that json instead it exist on another json which is the detail of specific item.
{
"xid":"N2180835380",
"name":"Stasiun Waytuba",
"address":{
"state":"Lampung",
"country":"Indonesia",
"village":"Way Tuba",
"postcode":"34767",
"country_code":"id"
},
"rate":"3",
"osm":"node/2180835380",
"wikidata":"Q19741325",
"kinds":"industrial_facilities,railway_stations,interesting_places",
"sources":{
"geometry":"osm",
"attributes":[
"osm",
"wikidata"
]
},
"otm":"https://opentripmap.com/en/card/N2180835380",
"wikipedia":"https://id.wikipedia.org/wiki/Stasiun%20Way%20Tuba",
"image":"https://commons.wikimedia.org/wiki/File:Stasiun_Waytuba_08-2015.jpg",
"preview":{
"source":"https://upload.wikimedia.org/wikipedia/commons/thumb/f/fe/Stasiun_Waytuba_08-2015.jpg/400px-Stasiun_Waytuba_08-2015.jpg",
"height":293,
"width":400
},
"wikipedia_extracts":{
"title":"id:Stasiun Way Tuba",
"text":"Stasiun Way Tuba (WAY) adalah stasiun kereta api kelas II yang berada di Way Tuba, Way Tuba, Way Kanan. Stasiun yang terletak pada ketinggian +81 meter ini termasuk ke dalam Divisi Regional IV Tanjungkarang. Stasiun ini mempunyai 2 jalur rel dengan jalur 2 merupakan sepur lurus.Semua perjalanan kereta api yang melayani rute Kertapati–Tanjungkarang pasti berhenti di stasiun ini.",
"html":"<p><b>Stasiun Way Tuba</b> (<b>WAY</b>) adalah stasiun kereta api kelas II yang berada di Way Tuba, Way Tuba, Way Kanan. Stasiun yang terletak pada ketinggian +81 meter ini termasuk ke dalam Divisi Regional IV Tanjungkarang. Stasiun ini mempunyai 2 jalur rel dengan jalur 2 merupakan sepur lurus.</p><p>Semua perjalanan kereta api yang melayani rute Kertapati–Tanjungkarang pasti berhenti di stasiun ini.</p>"
},
"point":{
"lon":104.411728,
"lat":-4.379512
}
}
That was a json data that contain the detail of place on the first list.
Here is my code, for now i just display the list only with name and rating, since i don't know how to fetch image url inside the JsonArrayRequest.
package com.example.explorev10;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
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.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class PlaceListActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private PlaceAdapter mPlaceAdapter;
private ArrayList<PlaceItem> mPlaceList;
private RequestQueue mRequestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_place_list);
mRecyclerView = findViewById(R.id.recycle_view_place_list);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mPlaceList = new ArrayList<>();
mRequestQueue = Volley.newRequestQueue(this);
parseJSON();
}
private void parseJSON() {
String jsonURL = "https://api.opentripmap.com/0.1/en/places/bbox?lon_min=104.268781&lat_min=-5.780249&lon_max=105.755215&lat_max=-4.101807&kinds=interesting_places&format=json&apikey=5ae2e3f221c38a28845f05b65ba166329393551235361ab9b66e2889";
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, jsonURL, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject place = response.getJSONObject(i);
String placeName = place.getString("name");
int placeRating = place.getInt("rate");
String imageURL = "";
mPlaceList.add(new PlaceItem(imageURL, placeName, placeRating));
}
mPlaceAdapter = new PlaceAdapter(PlaceListActivity.this, mPlaceList);
mRecyclerView.setAdapter(mPlaceAdapter);
} catch (JSONException e) {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mRequestQueue.add(request);
}
}
How can i access the place detail as JsonObject inside the for loop?
Can someone help me please?? Thank you so much ..
Sorry for the bad english
Along with name and rate store xid in Places pojo class and call second api in response listener of first api instead of calling recycler view, once second api response is completed pass the list to recycler view
private void parseSecondJSON() {
String jsonURL = "secondurl";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, jsonURL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
for (int i = 0; i < mPlaceList.size(); i++) {
if(mPlaceList.get(i).xid.equals(response.xid)) {
mPlaceList.get(i).image = response.image;
}
}
mPlaceAdapter = new PlaceAdapter(PlaceListActivity.this, mPlaceList);
mRecyclerView.setAdapter(mPlaceAdapter);
} catch (JSONException e) {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mRequestQueue.add(request);
}
Related
I am new to android and volley
I'm straggling with JSON path
spent a lot of time debugging this code but unfortunately could not find the bug, can someone help me find the issue in this code. I am not able to see data on the activity page
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import com.android.volley.AuthFailureError;
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;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class dailyshop extends AppCompatActivity {
private RecyclerView mRecycler;
private cardAdapter mCardAdapter;
private ArrayList<carditem> mCardList;
private RequestQueue mRequestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dailyshop);
mRecycler = findViewById(R.id.recycler_view);
mRecycler.setHasFixedSize(true);
mRecycler.setLayoutManager(new LinearLayoutManager(this));
mCardList = new ArrayList<>();
mRequestQueue = Volley.newRequestQueue(this);
parseJSON();
}
private void parseJSON(){
String url = "https://fortnite-api.theapinetwork.com/store/get";
final JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
String itemName = jsonObject.getString("name");
String imageUrl = jsonObject.getString("background");
int vCount = jsonObject.getInt("cost");
mCardList.add(new carditem(imageUrl,itemName,vCount));
}
mCardAdapter = new cardAdapter(dailyshop.this, mCardList);
mRecycler.setAdapter(mCardAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}
){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Authorization", "mycode");
return params;
}
};
mRequestQueue.add(request);
}
}
I tried to use custom API without key in same JSON child and it worked
api json file
{
"lastUpdate":1563408000,
"language":"en",
"data":[
{
"itemId":"0ac5766-6f9355e-6575a4e-abaef79",
"lastUpdate":1563408000,
"store":{
"isFeatured":false,
"isRefundable":true,
"cost":"500",
"occurrences":1,
"isNew":true
},
"item":{
"name":"Glitter",
"description":"",
"type":"emote",
"rarity":"rare",
"costmeticId":null,
"images":{
"icon":"https://fortnite-public-files.theapinetwork.com/emote/a7eb82676b96bc1ff2129ee739d70d4a.png",
"featured":null,
"background":"https://fortnite-public-files.theapinetwork.com/image/0ac5766-6f9355e-6575a4e-abaef79.png",
"information":"https://fortnite-public-files.theapinetwork.com/image/0ac5766-6f9355e-6575a4e-abaef79/item.png"
},
"backpack":{
},
"obtained_type":"vbucks",
"ratings":{
"avgStars":4.18,
"totalPoints":614,
"numberVotes":147
}
}
},
{
"itemId":"d2e8284-fb06feb-ea3fbe3-c41fd8b",
"lastUpdate":1563408000,
"store":{
"isFeatured":false,
"isRefundable":true,
"cost":"800",
"occurrences":3,
"isNew":false
},
"item":{
"name":"Star Wand",
"description":null,
"type":"pickaxe",
"rarity":"rare",
"costmeticId":null,
"images":{
"icon":"https://fortnite-public-files.theapinetwork.com/pickaxe/e0907bc2a6058035c5bf96820da6c21f.png",
"featured":null,
"background":"https://fortnite-public-files.theapinetwork.com/image/d2e8284-fb06feb-ea3fbe3-c41fd8b.png",
"information":"https://fortnite-public-files.theapinetwork.com/image/d2e8284-fb06feb-ea3fbe3-c41fd8b/item.png"
},
"backpack":{
},
"obtained_type":"vbucks",
"ratings":{
"avgStars":4.07,
"totalPoints":789,
"numberVotes":194
}
}
},
{
"itemId":"eb00ead-bb56b45-05e52f8-2398d3a",
"lastUpdate":1563408000,
"store":{
"isFeatured":false,
"isRefundable":true,
"cost":"300",
"occurrences":1,
"isNew":true
},
"item":{
"name":"Scanline",
"description":"",
"type":"wrap",
"rarity":"uncommon",
"costmeticId":null,
"images":{
"icon":"https://fortnite-public-files.theapinetwork.com/wrap/5677d39e97ba5bf8d92e25bc520e7cc0.png",
"featured":null,
"background":"https://fortnite-public-files.theapinetwork.com/image/eb00ead-bb56b45-05e52f8-2398d3a.png",
"information":"https://fortnite-public-files.theapinetwork.com/image/eb00ead-bb56b45-05e52f8-2398d3a/item.png"
},
"backpack":{
},
"obtained_type":"vbucks",
"ratings":{
"avgStars":4.82,
"totalPoints":164,
"numberVotes":34
}
}
},
{
"itemId":"a784814-93b4ea3-3c26b6f-631fac7",
"lastUpdate":1563408000,
"store":{
"isFeatured":false,
"isRefundable":true,
"cost":"500",
"occurrences":1,
"isNew":true
}
}
]
}
I need help with JSON path and if there is something wrong with my code
Try this:
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
String credentials = "username" + ":" + "password";
String base64EncodedCredentials = Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
HashMap<String, String> headers = new HashMap<>();
headers.put("Authorization", "Basic " + base64EncodedCredentials);
return headers;
}
I am Creating a App to get Json Data from Web service and Bind it to Bar Chart.
I dont know how to do this. am using MPAndroid library for charts.
help me bind bar chart data from JSON data.
web service:
[
{
"NAME": "601 GRIETA EN CUERPO",
"PERCENTAGE": "46"
},
{
"NAME": "77 ENFRIAMIENTO O DUNTING",
"PERCENTAGE": "18"
},
{
"NAME": "78 PRECALENTAMIENTO",
"PERCENTAGE": "18"
},
{
"NAME": "209 MAL MANEJO",
"PERCENTAGE": "9"
},
{
"NAME": "92 FUGA DE MANOMETRO",
"PERCENTAGE": "9"
}
]
Barchart. java
package com.example.saravanakumars.chart;
/**
* Created by saravanakumars on 9/18/2017.
*/
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.utils.ColorTemplate;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class barchart extends AppCompatActivity {
BarChart chart ;
ArrayList<BarEntry> BARENTRY ;
ArrayList<String> BarEntryLabels ;
BarDataSet Bardataset ;
BarData BARDATA ;
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
private static String url = "http://113.193.30.155/MobileService/MobileService.asmx/GetSampleData";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bar_chart);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
// bar chart
chart = (BarChart) findViewById(R.id.barchart);
BARENTRY = new ArrayList<>();
BarEntryLabels = new ArrayList<String>();
AddValuesToBARENTRY();
AddValuesToBarEntryLabels();
Bardataset = new BarDataSet(BARENTRY, "Projects");
BARDATA = new BarData(BarEntryLabels, Bardataset);
Bardataset.setColors(ColorTemplate.COLORFUL_COLORS);
chart.setData(BARDATA);
chart.animateY(3000);
}
});
// registerForContextMenu( txt1 );
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
{
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
menu.setHeaderTitle("Select The Action");
inflater.inflate( R.menu.popup_menu,menu );
}
#Override
public boolean onContextItemSelected(MenuItem item){
switch (item.getItemId()) {
case R.id.one:
Toast.makeText(barchart.this,"You Clicked : " + item.getTitle(),Toast.LENGTH_SHORT).show();
break;
case R.id.two:
Toast.makeText(barchart.this,"You Clicked : " + item.getTitle(),Toast.LENGTH_SHORT).show();
break;
}
return true;
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(barchart.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONArray array = new JSONArray(jsonStr);
for (int i = 0; i < array.length(); i++) {
JSONObject object = (JSONObject) array.get(i);
String NAME = object.getString("NAME");
String PERCENTAGE = object.getString("PERCENTAGE");
int minqty = Integer.parseInt(object.getString("PERCENTAGE"));
HashMap<String, String> contact = new HashMap<>();
BARENTRY.add(minqty);
contact.put("NAME", NAME);
contact.put("PERCENTAGE", PERCENTAGE);
// adding contact to contact list
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
}
}
}
Use gson to make object from your jSON:
YourModelClass yourModelClassObject = gson.fromJson(args[0].toString(), YourModelClass.class);
then get your arrayList and provide it to charts dataset
Use following link to make pojo from your JSON
http://www.jsonschema2pojo.org/
As an alternative, you can use wannacharts.com .. is a api like service, where you can post a Json in the url of the api and the response is a json with a base64 image of the chart (how to decode base64 image in android), or a url to png file with the chart.
the good part is that you dont have to use any external library!
Is free, but previously you must register and pre-set the chart in the chart designer.
Here are the faq's
Sorry if the question is a bit NEWSBIE type but I am not known to Android :(
So I have The MainActivity.Java that populates a TextView. I fetch data from server using JSON and it gives parameters as id, username, message, date_time, status, type.
What I want is on each Click of the List Item, It goes the website as follows:
http://my_web_site_url/json?id=id_of_the_list_item&status=something
i.e When User clicks on a single List Item, the url redirects using the same id that is retrieved by JSON and is of Each List Item.
How to set and then get each list_item_id and how to go to the website?
Any Help is Appreciated!
My code is:
package something;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
// URL to get contacts JSON
private static String url = "my_website_that_returns_json_data";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
*/
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray result = jsonObj.getJSONArray("result");
// looping through All Contacts
for (int i = 0; i < result.length(); i++) {
JSONObject c = result.getJSONObject(i);
String id = c.getString("id");
String username = c.getString("username");
String message = c.getString("message");
String date_status = "Date: " + c.getString("date_time") + " Status: " + c.getString("status");
// tmp hash map for single contact
HashMap<String, String> result1 = new HashMap<>();
// adding each child node to HashMap key => value
result1.put("id", id);
result1.put("username", username);
result1.put("message", message);
result1.put("date_status", date_status);
// adding contact to contact list
contactList.add(result1);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[]{"username", "message",
"date_status"}, new int[]{R.id.username,
R.id.message,R.id.date_status});
lv.setAdapter(adapter);
}
}
}
Use onItemClickListener in your ListView
example using inner class
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick((AdapterView<?> parent,
View view,
int position,
long id)) {
String item = lv.getItemAtPosition(position);
Toast.makeText(this,"You selected : " + item,Toast.LENGTH_SHORT).show();
}
});
in your method you will get position of your data and load your link.
I need to pass the brand id values of my json response as a parameter to http request using shared preference.I also need to store the brand id values in my main Activity and retreive it in my AddVehicle activity Please help me.Can i use arraylist? If yes, Then say me how? The id should check with the corresponding name and it should be displayed on my 2nd activity(AddVehicle)
Currently i have passed only one brand detail in my main Activity,but instead i need to pass all the id dynamically under one common variable?
My API response
{
"status": 1,
"data": [
{
"id": 1,----> brand id
"name": "AUDI",
"code": "AUDI",
"image": "",
"status": "1",
"created_at": "2016-09-27 00:07:38",
"updated_at": "2016-09-27 00:07:38"
},
{
"id": 2-----> brand id
"name": "Bravian Motor Works",
"code": "BMW",
"image": "",
"status": "1",
"created_at": "2016-09-27 00:07:58",
"updated_at": "2016-09-27 00:07:58"
},
{
"id": 3,---->brand id
"name": "AB Volvo",
"code": "VOLVO",
"image": "",
"status": "1",
"created_at": "2016-09-27 00:08:36",
"updated_at": "2016-09-27 00:08:36"
},
{
"id": 4,-----> brand id
"name": "Ford Motor Company",
"code": "FORD",
"image": "",
"status": "1",
"created_at": "2016-09-27 00:11:51",
"updated_at": "2016-09-27 00:11:51"
},
{
"id": 5,-----> brand id
"name": "Maruti Suzuki",
"code": "Maruti",
"image": "",
"status": "1",
"created_at": "2016-09-27 00:12:14",
"updated_at": "2016-09-27 00:12:14"
}
],
"msg": "success",
"info": "data list"
}
MainActivity
package com.example.addvehicle;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONArray;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static com.example.addvehicle.R.string.brand;
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
ArrayList<String> brandListArray = new ArrayList<String>();
ArrayList<String> modelListArray = new ArrayList<String>();
Button addVehicleBtn;
EditText AddVehicle_Regno, kmscovered;
RadioButton petrol, Diesel, fullyloaded, Basicmodel;
TextView textView8, textViewkms;
Spinner AddspinnerMake, AddspinnerModel, AddspinnerYear;
private static String url = "http://garage.kaptastech.mobi/api/5k/master/vehicle";
private String[] values;
ArrayList<String> brandListId;
ArrayList<String> modelListId;
String brandid;
String modelId;
ArrayList<HashMap<String, String>> addVehiclelist;
String jsonStr;
String Regno, fuelType, Brand, Year, Model, variant;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
brandListArray = new ArrayList<String>();
brandListId = new ArrayList<String>();
modelListArray = new ArrayList<String>();
modelListId = new ArrayList<String>();
addVehiclelist = new ArrayList<HashMap<String, String>>();
petrol = (RadioButton) findViewById(R.id.petrol);
Diesel = (RadioButton) findViewById(R.id.diesel);
fullyloaded = (RadioButton) findViewById(R.id.fullyLoaded);
Basicmodel = (RadioButton) findViewById(R.id.basicmodel);
addVehicleBtn = (Button) findViewById(R.id.addVehicleBtn);
AddVehicle_Regno = (EditText) findViewById(R.id.AddVehicle_Regno);
kmscovered = (EditText) findViewById(R.id.kmsCovered);
textView8 = (TextView) findViewById(R.id.textView8);
textViewkms = (TextView) findViewById(R.id.textViewkms);
AddspinnerMake = (Spinner) findViewById(R.id.AddspinnerMake);
AddspinnerModel = (Spinner) findViewById(R.id.AddspinnerModel);
AddspinnerYear = (Spinner) findViewById(R.id.AddspinnerYear);
new Getbrands().execute();
petrol.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (petrol.isChecked()) {
fuelType = petrol.getText().toString();
}
}
});
Diesel.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (Diesel.isChecked()) {
fuelType = Diesel.getText().toString();
}
}
});
AddspinnerMake.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
Brand = AddspinnerMake.getSelectedItem().toString();
if (position > 0) {
brandid = brandListId.get(position).toString();
//**Get Model execute api//
new Getmodels().execute();
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
AddspinnerYear.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Year = AddspinnerYear.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
AddspinnerModel.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
Model = AddspinnerModel.getSelectedItem().toString();
if (position > 0) {
modelId = modelListId.get(position).toString();
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
Basicmodel.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (Basicmodel.isChecked()) {
variant = Basicmodel.getText().toString();
}
}
});
fullyloaded.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (fullyloaded.isChecked()) {
variant = fullyloaded.getText().toString();
}
}
});
addVehicleBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Regno = AddVehicle_Regno.getText().toString();
new GetVehicle().execute();
Intent intent = new Intent(MainActivity.this, AddVehicle.class);
startActivity(intent);
}
});
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
public Action getIndexApiAction() {
Thing object = new Thing.Builder()
.setName("Main Page") // TODO: Define a title for the content shown.
// TODO: Make sure this auto-generated URL is correct.
.setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
.build();
return new Action.Builder(Action.TYPE_VIEW)
.setObject(object)
.setActionStatus(Action.STATUS_TYPE_COMPLETED)
.build();
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
AppIndex.AppIndexApi.start(client, getIndexApiAction());
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
AppIndex.AppIndexApi.end(client, getIndexApiAction());
client.disconnect();
}
private class GetVehicle extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://garage.kaptastech.mobi/api/5k/master/vehicle");
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(7);
nameValuePair.add(new BasicNameValuePair("user_id","5"));
nameValuePair.add(new BasicNameValuePair("registration_no", Regno));
nameValuePair.add(new BasicNameValuePair("brand","5"));
nameValuePair.add(new BasicNameValuePair("model", "4"));
nameValuePair.add(new BasicNameValuePair("type", "2"));
nameValuePair.add(new BasicNameValuePair("variant", "2"));
nameValuePair.add(new BasicNameValuePair("year", Year));
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
} catch (UnsupportedEncodingException e) {
// writing error to Log
e.printStackTrace();
}
// Making HTTP Request
try {
HttpResponse response = client.execute(httpPost);
// writing response to log
Log.d("Response from url:", response.toString());
jsonStr = EntityUtils.toString(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
try {
/*HttpConnection ht = new HttpConnection();
ht.getVehicle();*/
JSONObject object = new JSONObject(jsonStr);
JSONArray Vehicle = object.getJSONArray("data");
for (int i = 0; i < Vehicle.length(); i++) {
JSONObject c = Vehicle.getJSONObject(i);
String Regno = c.getString("registration_no");
String brand = c.getString("brand");
String model = c.getString("model");
String fueltype = c.getString("type");
String variant = c.getString("variant");
HashMap<String, String> Vl = new HashMap<String, String>();
Vl.put("registration_no", Regno);
Vl.put("brand", brand);
Vl.put("model", model);
Vl.put("type", fueltype);
Vl.put("variant:", variant);
addVehiclelist.add(Vl);
values = new String[]{
"Registration No:" + Regno,
"Brand:" + brand,
"Model:" + model,
"Type:" + fueltype,
"Variant:" + variant,
};
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
}
private class Getbrands extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://garage.kaptastech.mobi/api/5k/master/brand");
try {
HttpResponse response = client.execute(httpGet);
// writing response to log
Log.d("Response from url:", response.toString());
jsonStr = EntityUtils.toString(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
try {
HttpConnection ht = new HttpConnection();
ht.getbrand();
JSONObject object = new JSONObject(jsonStr);
JSONArray brandArray = object.getJSONArray("data");
brandListArray.clear();
brandListId.clear();
brandListArray.add("Select Brand");
brandListId.add("0");
for (int i = 0; i < brandArray.length(); i++) {
JSONObject gb = brandArray.getJSONObject(i);
brandListArray.add(gb.getString("name"));
brandListId.add(gb.getString("id"));
String[] brandStringArray = new String[brandListArray.size()];
brandStringArray = brandListArray.toArray(brandStringArray);
for (int i1 = 0; i1 < brandStringArray.length; i1++) {
Log.d("String is", (String) brandStringArray[i1]);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, brandListArray);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
AddspinnerMake.setAdapter(adapter);
}
}
private class Getmodels extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://garage.kaptastech.mobi/api/5k/master/models/" + brandid);
try {
HttpResponse response = client.execute(httpGet);
// writing response to log
Log.d("Response from url:", response.toString());
jsonStr = EntityUtils.toString(response.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
try {
HttpConnection ht = new HttpConnection();
ht.getmodel();
JSONObject object = new JSONObject(jsonStr);
JSONArray modelArray = object.getJSONArray("data");
modelListArray.clear();
modelListId.clear();
modelListArray.add("Select Model");
modelListId.add("0");
for (int i = 0; i < modelArray.length(); i++) {
JSONObject gm = modelArray.getJSONObject(i);
modelListArray.add(gm.getString("name"));
modelListId.add(gm.getString("id"));
String[] modelStringArray = new String[modelListArray.size()];
modelStringArray = modelListArray.toArray(modelStringArray);
for (int i2 = 0; i2 < modelStringArray.length; i2++) {
Log.d("String is", (String) modelStringArray[i2]);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, modelListArray);
AddspinnerModel.setAdapter(adapter);
}
}
}
And i need to retreive it on my AddVehicle Activity
AddVehicleActivity
package com.example.addvehicle;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class AddVehicle extends AppCompatActivity {
ListView addVehicleListView;
ArrayList<HashMap<String, String>> VehicleList;
ArrayList<String> brandListId;
private String[] values;
private static String urlString = "http://garage.kaptastech.mobi/api/5k/users/vehicle";
private String TAG = AddVehicle.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
brandListId = new ArrayList<String>();
VehicleList = new ArrayList<HashMap<String, String>>();
addVehicleListView = (ListView) findViewById(R.id.addVehicleListView);
new GetVehicle().execute();
}
private class GetVehicle extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
HttpConnection ht = new HttpConnection();
String response = ht.getVehicle();
{
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet("http://garage.kaptastech.mobi/api/5k/users/vehicle");
JSONObject Object = new JSONObject(response);
JSONArray Vehicle = Object.getJSONArray("data");
for (int i = 0; i < Vehicle.length(); i++) {
JSONObject c = Vehicle.getJSONObject(i);
String Regno = c.getString("registration_no");
String brand = c.getString("brand_id");
String model = c.getString("model_id");
String fueltype = c.getString("type");
String variant = c.getString("variant");
HashMap<String, String> Vl = new HashMap<String, String>();
Vl.put("registration_no", Regno);
Vl.put("brand_id", brand);
Vl.put("model_id", model);
Vl.put("type", fueltype);
Vl.put("variant:" , variant);
VehicleList.add(Vl);
values = new String[]{
"Registration No:" + Regno,
"Brand Id:" + brand,
"Model Id:" + model,
"Type:" + fueltype,
"Variant:" + variant,
};
}
} catch (final Exception e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(AddVehicle.this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
//ListAdapter adapter = new SimpleAdapter(AddVehicle.this, VehicleList, R.layout.activity_list, new String[]{"brand_id", "model_id", "registration_no", "type", "variant"}, new int[]{R.id.AddspinnerMake, R.id.AddspinnerModel, R.id.AddVehicle_Regno, R.id.fullyLoaded, R.id.basicmodel});
addVehicleListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
}
I have a problem to view a date that I receive from my database. Let me explain what I'm doing. I have a database where there is a table called rate1 which is formed from a single column called value which it contains double numbers. My intent is to take all the data in this column, do the average and return it in my java code. I wanto to display the average in a TextView. My problem is that I do not see anything on the TextView. Can anyone tell me where I'm wrong, and if can he give me solutions to my mistakes? Now I add the code:
This is the Average.java:
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Average extends AppCompatActivity {
private TextView textViewResult;
private ProgressDialog loading;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_average);
textViewResult = (TextView) findViewById(R.id.textViewResult);
loading = ProgressDialog.show(this,"Please wait...","Fetching...",false,false);
String url = Config.DATA_URL.toString().trim();
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(Average.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String response){
String name="";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
JSONObject collegeData = result.getJSONObject(0);
name = collegeData.getString(Config.KEY_NAME);
} catch (JSONException e) {
e.printStackTrace();
}
textViewResult.setText("Name:\t"+name);
}
}
This is the Config.java:
public class Config {
public static final String DATA_URL = "https://lbstudios.000webhostapp.com/Average.php";
public static final String KEY_NAME = "value";
public static final String JSON_ARRAY = "result";
}
And this is Average.php:
<?php
$connect = mysqli_connect("********", "********", "********", "*******");
$response = mysqli_query($connect, 'SELECT AVG(value) AS average FROM rate1');
$result = array();
if ($response) {
/* fetch associative array */
while ($row = mysqli_fetch_assoc($response)) {
$result[] = $row;
}
/* free result set */
mysqli_free_result($result);
}
echo json_encode($result);
?>
I think that the a little problem comes up here;
JSONObject jsonObject = new JSONObject(response);
And
JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
Let's suppose that the connection is established successfully with the server and $result array is returned as response.
In this particular case, the json array returned by the json_encode function is not wrapped with the name result. Instead they are just wrapped JSON objects connected together.
The possible solution I can come up with is to delete the above lines I mentioned and replace them with;
try {
JSONArray result = new JSONArray(response);
for(int i=0; i<result.length(); i++){
JSONObject obj = result.getJSONObject(i);
// Proceed with your logic with each object accordingly.
}
} catch (JSONException e) { e.printStackTrace();
}