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
Related
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);
}
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.
please help how can i solve that in \AboutActivity.java
in the line :
imageLoader.DisplayImage(Constant.SERVER_IMAGE_NEWSLISTDETAILS+about.getComLogo().toString(), imglogo);
the problem in messages gradle builder :
Error:Error: Expected resource of type string [ResourceType]
package com.freeimages.hdpicturs;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.hdpictursfree.imageloader.ImageLoader;
import com.hdpictursfree.item.ItemAbout;
import com.hdpictursfree.util.AlertDialogManager;
import com.hdpictursfree.util.Constant;
import com.hdpictursfree.util.JsonUtils;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class AboutActivity extends ActionBarActivity {
ImageView imglogo;
TextView txtappname,txtcomemail,txtcomsite;
WebView webcomdes;
public ImageLoader imageLoader;
JsonUtils util;
List<ItemAbout> listabout;
AlertDialogManager alert = new AlertDialogManager();
Toolbar toolbar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.about);
toolbar = (Toolbar) this.findViewById(R.id.toolbar);
toolbar.setTitle("About Us");
this.setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
imglogo=(ImageView)findViewById(R.id.image_comlogo);
txtappname=(TextView)findViewById(R.id.text_appname);
txtcomemail=(TextView)findViewById(R.id.text_comemail);
txtcomsite=(TextView)findViewById(R.id.text_comwebsite);
webcomdes=(WebView)findViewById(R.id.webView_comdes);
webcomdes.getSettings().setDefaultTextEncodingName("UTF-8");
listabout=new ArrayList<ItemAbout>();
imageLoader=new ImageLoader(getApplicationContext());
util=new JsonUtils(getApplicationContext());
if (JsonUtils.isNetworkAvailable(AboutActivity.this)) {
new MyTask().execute(Constant.COMPANY_DETAILS_URL);
} else {
showToast("No Network Connection!!!");
alert.showAlertDialog(AboutActivity.this, "Internet Connection Error",
"Please connect to working Internet connection", false);
}
}
private class MyTask extends AsyncTask<String, Void, String> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AboutActivity.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
return JsonUtils.getJSONString(params[0]);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (null != pDialog && pDialog.isShowing()) {
pDialog.dismiss();
}
if (null == result || result.length() == 0) {
showToast("Server Connection Error");
alert.showAlertDialog(AboutActivity.this, "Server Connection Error",
"May Server Under Maintaines Or Low Network", false);
} else {
try {
JSONObject mainJson = new JSONObject(result);
JSONArray jsonArray = mainJson.getJSONArray(Constant.CATEGORY_ARRAY_NAME);
JSONObject objJson = null;
for (int i = 0; i < jsonArray.length(); i++) {
objJson = jsonArray.getJSONObject(i);
ItemAbout objItem = new ItemAbout();
objItem.setAppName(objJson.getString(Constant.COMPANY_DETAILS_APPNAME));
objItem.setComEmail(objJson.getString(Constant.COMPANY_DETAILS_COMMAIL));
objItem.setComWebsite(objJson.getString(Constant.COMPANY_DETAILS_COMSITE));
objItem.setComDes(objJson.getString(Constant.COMPANY_DETAILS_COMDES));
objItem.setComLogo(objJson.getString(Constant.COMPANY_DETAILS_COMLOGO));
listabout.add(objItem);
}
} catch (JSONException e) {
e.printStackTrace();
}
setAdapterToListview();
}
}
}
public void setAdapterToListview() {
ItemAbout about=listabout.get(0);
txtappname.setText(about.getAppName());
txtcomemail.setText(about.getComEmail());
txtcomsite.setText(about.getComWebsite());
String mimeType = "text/html";
String encoding = "utf-8";
String htmlText = about.getComDes();
String text = "<html><head>"
+ "<style type=\"text/css\">body{color: #1C1C1C;}"
+ "</style></head>"
+ "<body>"
+ htmlText
+ "</body></html>";
webcomdes.loadData(text, mimeType, encoding);
webcomdes.setBackgroundColor(Color.parseColor(getString(R.color.background_color)));
imageLoader.DisplayImage(Constant.SERVER_IMAGE_NEWSLISTDETAILS+about.getComLogo().toString(), imglogo);
}
public void showToast(String msg) {
Toast.makeText(AboutActivity.this, msg, Toast.LENGTH_LONG).show();
}
#Override
public boolean onOptionsItemSelected(MenuItem menuItem)
{
switch (menuItem.getItemId())
{
case android.R.id.home:
onBackPressed();
break;
default:
return super.onOptionsItemSelected(menuItem);
}
return true;
}
}
i am working on json parsing where in my TypeMenu java file i am getting response from server and when i click on the item in listview i should get related item in the next activity in listview ..that listview item is also coming from server...here i want to get item only from selected item..but i am getting all item from database in my next activity which is SubMenu.java...like if i select Pizza so in next activity i should get item related with pizza only
Here is my TypeMenu.java file
package com.example.zeba.broccoli;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
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 TypeMenu extends AppCompatActivity {
private String TAG = TypeMenu.class.getSimpleName();
String bid;
private ProgressDialog pDialog;
private ListView lv;
private static final String TAG_BID = "bid";
// URL to get contacts JSON
private static String url = "http://cloud.granddubai.com/brtemp/index.php";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_type_menu);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// getting values from selected ListItem
HashMap<String, String> selected = contactList.get(position);
String keyId = new ArrayList<>(selected.keySet()).get(0);
String type_items = selected.get(keyId);
Intent in = new Intent(getApplicationContext(), SubMenu.class);
// sending pid to next activity
in.putExtra(TAG_BID ,type_items );
startActivityForResult(in, 100);
Toast.makeText(getApplicationContext(),"Toast" +type_items ,Toast.LENGTH_LONG).show();
}
});
}
/**
* 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(TypeMenu.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
// Toast.makeText(getApplicationContext(),"Toast",Toast.LENGTH_LONG).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 jsonArry = new JSONArray(jsonStr);
for (int i = 0; i < jsonArry.length(); i++)
{
JSONObject c = jsonArry.getJSONObject(i);
String id = c.getString("id");
String type = c.getString("type");
HashMap<String, String> contact = new HashMap<>();
contact.put("id", id);
contact.put("type", type);
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();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
TypeMenu.this, contactList,
R.layout.list_item, new String[]{ "type","id"},
new int[]{
R.id.type,R.id.id});
lv.setAdapter(adapter);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
here is my SubMenu.java file
package com.example.zeba.broccoli;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
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 SubMenu extends AppCompatActivity {
private String TAG = SubMenu.class.getSimpleName();
String type_items ;
private ProgressDialog pDialog;
private ListView lv;
private static final String TAG_BID = "bid";
// URL to get contacts JSON
private static String url = "http://cloud.granddubai.com/broccoli/menu_typeitem.php";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_type_menu);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Intent i = getIntent();
// getting product id (pid) from intent
type_items = i.getStringExtra(TAG_BID);
Toast.makeText(getApplicationContext(),"Toast 12" + type_items ,Toast.LENGTH_LONG).show();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
pDialog = new ProgressDialog(SubMenu.this);
pDialog.setMessage("Loading book details.");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
// getting values from selected ListItem
HashMap<String, String> selected = contactList.get(position);
String keyId = new ArrayList<>(selected.keySet()).get(0);
String type_items = selected.get(keyId);
//Intent in = new Intent(getApplicationContext(), SubMenu.class);
// sending pid to next activity
// in.putExtra(TAG_BID ,text);
//startActivityForResult(in, 100);
Toast.makeText(getApplicationContext(),"Toast" + type_items,Toast.LENGTH_LONG).show();
}
});
}
/**
* 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(SubMenu.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
// Toast.makeText(getApplicationContext(),"Toast",Toast.LENGTH_LONG).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 jsonArry = new JSONArray(jsonStr);
for (int i = 0; i < jsonArry.length(); i++)
{
JSONObject c = jsonArry.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
HashMap<String, String> contact = new HashMap<>();
contact.put("id", id);
contact.put("name", name);
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();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
SubMenu.this, contactList,
R.layout.list_item, new String[]{ "name","id"},
new int[]{
R.id.type});
lv.setAdapter(adapter);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
here is my php file..i know it will show all the data ..i tried other code also but not working ..in this atleast all data from table is showing..but i want only selected data
<?php
if($_SERVER['REQUEST_METHOD']=='GET')
{
$id = $_GET['type_items'];
require_once('config.php');
$sql = "SELECT * FROM main_menu_items WHERE type_item='".$id."'";
$r = mysqli_query($con,$sql);
$res = mysqli_fetch_array($r);
$result = array();
array_push($result,array("name"=>$res['name'],)
);
echo json_encode(array("result"=>$result));
mysqli_close($con);
}
replace for loop of GetContacts of SubMenu.java class with below :
for (int i = 0; i < jsonArry.length(); i++) {
JSONObject c = jsonArry.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
String type = c.getString("type");
if (type.equalsIgnoreCase(type_items)) {
HashMap<String, String> contact = new HashMap<>();
contact.put("id", id);
contact.put("name", name);
contactList.add(contact);
break;
}
}
In submenu class you need to check if the selected ID matches with the id just save that data in list and break the loop.
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();
}
}
}