How to make seat layouts like in redbus? - android

How to give space inside a grid view in after 3 elements in each row?
expected view is given below:
.
This is my main activity code.
please check my screen that i given above
i want a space inside grid view in android,How to give space inside a grid view in after 3 elements in each row ?
public void submit() {
String URLL= "https://api.myjson.com/bins/14h7rp";
StringRequest stringRequest = new StringRequest(Request.Method.GET, URLL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject object=new JSONObject(response);
String status=object.getString("Status");
String Data=object.getJSONObject("Data").getString("Seat_details");
JSONArray jsonArray=new JSONArray(Data);
for (int i=0;i<jsonArray.length();i++){
JSONObject J=jsonArray.getJSONObject(i);
String seats=J.getString("seats");
JSONArray jsonArray1=new JSONArray(seats);
for (int k=0;k<jsonArray1.length();k++){
JSONObject l=jsonArray1.getJSONObject(k);
String id=l.getString("id");
String name=l.getString("name");
String bookedStatus=l.getString("bookedStatus");
m=new Model();
m.setId(id);
m.setName(name);
m.setBookedStatus(bookedStatus);
arrayList.add(m);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter=new MainActivityAdapter(arrayList,MainActivity.this);
recyclerView.setAdapter(adapter);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
}
}
my Recylerview initialization is below
private void init_views() {
recyclerView=(RecyclerView)findViewById(R.id.recyclerview);
int spacingInPixels = getResources().getDimensionPixelSize(R.dimen.spacing);
recyclerView.addItemDecoration(new SpacesItemDecoration(spacingInPixels));
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(),5);
recyclerView.setLayoutManager(layoutManager);
/* DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(),
layoutManager.getOrientation(layoutManager));
recyclerView.addItemDecoration(dividerItemDecoration);*/
}

one of the way u'l get the answer ,but its not a proper way
try {
JSONObject object=new JSONObject(response);
String status=object.getString("Status");
String Data=object.getJSONObject("Data").getString("Seat_details");
// System.out.println("_______Data_________" + Data);
JSONArray jsonArray=new JSONArray(Data);
for (int i=0;i<jsonArray.length();i++){
JSONObject J=jsonArray.getJSONObject(i);
String seats=J.getString("seats");
JSONArray jsonArray1=new JSONArray(seats);
for (int k=0;k<jsonArray1.length();k++){
if (k%COLUMNS==3) {
m=new Model();
m.setId("");
m.setName("");
m.setSeatKey("");
m.setRowNumber("");
m.setColumnIndex("");
m.setBookedStatus("2");
arrayList.add(m);
} else{
JSONObject l=jsonArray1.getJSONObject(k);
String id=l.getString("id");
String name=l.getString("name");
String seatKey=l.getString("seatKey");
String rowNumber=l.getString("rowNumber");
String columnIndex=l.getString("columnIndex");
String bookedStatus=l.getString("bookedStatus");
System.out.println("______name_________" + name);
m=new Model();
m.setId(id);
m.setName(name);
m.setSeatKey(seatKey);
m.setRowNumber(rowNumber);
m.setColumnIndex(columnIndex);
m.setBookedStatus(bookedStatus);
arrayList.add(m);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Declare COLUMN Variable
private static final int COLUMNS = 6;

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);

ArrayList won't populate ListView but I can display the items added to ArrayList

I don't know why the items added to ArrayList won't populate ListView, I tried checking if items are indeed added to ArrayList but it shows it does.
You can check the image of the added items here
Here is my code. I'm using another xml for checkedtextview so my listview will display items with checkboxes.
ArrayList<String> symptomsListTest = new ArrayList<>();
ListView chl1;
String URL = "***********";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sample);
addListItem();
chl1 = (ListView) findViewById(R.id.checklistSample);
chl1.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
ArrayAdapter<String> aa = new ArrayAdapter<String>(this, R.layout.symptoms_checklist, R.id.txt_title, symptomsListTest);
//ArrayAdapter<String> aa=new ArrayAdapter<String>(this,R.layout.symptoms_checklist, R.id.txt_title,symptomsListTest);
chl1.setAdapter(aa);
chl1.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
String selectedItem = ((TextView) view).getText().toString();
if(symptomsListTest.contains(selectedItem))
{
symptomsListTest.remove(selectedItem); //remove deselected item from the list of selected items
}
else
{
symptomsListTest.add(selectedItem); //add selected item to the list of selected items
}
}
});
}
public void addListItem()
{
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
try
{
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
String message = jsonObject.getString("message");
JSONArray jsonArray = jsonObject.getJSONArray("read");
if(success.equals("1"))
{
for(int i = 0; i < jsonArray.length(); i++)
{
JSONObject object = jsonArray.getJSONObject(i);
String symptom = object.getString("symptom1");
symptomsListTest.add(symptom);
//Toast.makeText(SAMPLE.this, ""+symptom, Toast.LENGTH_SHORT).show();
//Toast.makeText(Login.this, ""+message+"\nYour name is: "+name+"\nYour email is: "+email,Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(SAMPLE.this, ""+message,Toast.LENGTH_SHORT).show();
}
}
catch (JSONException e)
{
e.printStackTrace();
Toast.makeText(SAMPLE.this, e.toString(),Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(SAMPLE.this, error.toString(),Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError
{
Map<String, String> params = new HashMap<>();
String result="success";
params.put("result", result);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
You are executing an AsyncTask which is giving a response after sometime, meanwhile the code of listView and it's adapter is already executed. You just need to add one line after the for loop like this :-
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
String symptom = object.getString("symptom1");
symptomsListTest.add(symptom);
//Toast.makeText(SAMPLE.this, ""+symptom, Toast.LENGTH_SHORT).show();
//Toast.makeText(Login.this, ""+message+"\nYour name is: "+name+"\nYour email is: "+email,Toast.LENGTH_SHORT).show();
}
//** Add This line **
aa.notifyDataSetChanged();
And make sure your ArrayAdapter is declared global. Hope this helps.

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

having trouble fetching json into a fragment

Im having trouble fetching json data into a fragment and i need help. I dont know where im going wrong.
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.crime_fragment,container);
RecyclerView rv = (RecyclerView)v.findViewById(R.id.recyclerCrime);
//gives the context of the parent activity
rv.setLayoutManager(new LinearLayoutManager(this.getActivity()));
rv.setAdapter(new OtherAdapter(this.getActivity(),fetchJSon()));
MySingleton.getInstance(this.getContext()).addToRequestQueue(stringRequest);
return v;
}
private ArrayList<ListItem> fetchJSon() {
final ArrayList<ListItem> items = new ArrayList<ListItem>();
stringRequest = new StringRequest(Request.Method.GET, urlData, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
for(int i = 0;i<jsonArray.length();i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
ListItem listItem = new ListItem(jsonObject.getString("name"),jsonObject.getString("createdBy"),jsonObject.getString("imageUrl"));
items.add(listItem);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
return items;
}
StringRequest send an async request which means the response come back a few seconds later to the main thread. But in the meantime main thread reads the other code blocks.
So you must send the request first. You can fill the list when the response come successfully.
View v = inflater.inflate(R.layout.crime_fragment, container);
RecyclerView rv = (RecyclerView) v.findViewById(R.id.recyclerCrime);
//gives the context of the parent activity
fetchJSon(rv);
return v;
}
private void fetchJSon(final RecyclerView rv) {
final ArrayList < ListItem > items = new ArrayList < ListItem > ();
stringRequest = new StringRequest(Request.Method.GET, urlData, new Response.Listener < String > () {#
Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
ListItem listItem = new ListItem(jsonObject.getString("name"), jsonObject.getString("createdBy"), jsonObject.getString("imageUrl"));
items.add(listItem);
}
rv.setLayoutManager(new LinearLayoutManager(this.getActivity()));
rv.setAdapter(new OtherAdapter(this.getActivity(),items));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {#
Override
public void onErrorResponse(VolleyError error) {}
});
MySingleton.getInstance(this.getContext()).addToRequestQueue(stringRequest);
}

how to parse json object and json array in listview android

I am beginner to android app. I am facing trouble how to parse json object and json array to listview in android. Here is my json output
UPDATED WITH JSON CORRECTION
{status: "ok", listUsers: [{"id":2,"username":"myusername","name":"myname","email":"myemail","password":"mypassword","groupid":1,"type":"mytype"},{"id":3,"username":"myusername","name":"myname","email":"myemail2","password":"mypassword2","groupid":1,"type":"mytype"},{"id":4,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":5,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":6,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":7,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":8,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":9,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":10,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":11,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"1"},{"id":12,"username":"username1","name":"name1","email":"email1","password":"pass1","groupid":1,"type":"type1"},{"id":13,"username":"yuwah","name":"yu","email":"mail#gmail.com","password":"pass1","groupid":1,"type":"type1"},{"id":14,"username":"myusername","name":"myname","email":"myemail2","password":"mypassword2","groupid":1,"type":"mytype"}] }
Can anyone explain me how to do it. I am searching all over the topics but I still can't get it. Thanks.
Here is my code block
public class MainActivity extends ListActivity {
String url = "http://staging.workberryplus.com/mobile/listUsers/1";
ProgressDialog PD;
ArrayList<String> listUsers;
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listUsers = new ArrayList<String>();
PD = new ProgressDialog(this);
PD.setMessage("Loading.....");
PD.setCancelable(false);
adapter = new ArrayAdapter(this, R.layout.items, R.id.tv, listUsers);
setListAdapter(adapter);
MakeJsonArrayReq();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
}
private void MakeJsonArrayReq() {
PD.show();
//JsonArrayRequest jr=new JsonArrayRequest(url, listener, errorListener)
final StringRequest jreq = new StringRequest(url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
for (int i = 0; i < response.length(); i++) {
try {
Log.d("Response","->"+response);
JSONObject jo = new JSONObject(response);
JSONArray jarray = jo.getJSONArray("listUsers");
JSONObject jo2 = jarray.getJSONObject(i);
String name = jo2.getString("name");
listUsers.add(name);
} catch (JSONException e) {
e.printStackTrace();
}
}
PD.dismiss();
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
MyApplication.getInstance().addToReqQueue(jreq, "jreq");
}
}
try {
JSONObject jo = new JSONObject(response);
JSONArray jarray =jo.getJSONArray("listUsers");
for (int i = 0; i < jarray.length(); i++){
JSONObject jo2 = jarray.getJSONObject(i);
String name = jo2.getString("name");
listUsers.add(name);
}
} catch (JSONException e) {
e.printStackTrace();
}
Convert your String which is response to Json Object
JSONObject jsonObj = new JSONObject(response);
Then do the following
try {
if (jsonObj != null) {
if (jsonObj.optString("status").equals("ok")) {
JSONArray jsonArray = jsonObj.optJSONArray("listUsers");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.optJSONObject(i);
if (jsonObject != null) {
//Do work here
}
}
}
}
}catch (Exception e1) {
e1.printStackTrace();
}
try this and make changes accordingly and let me know if it work for you or not
JSONObject jo2 = jarray.getJSONObject(i);
You are iterating over the length of the response (a string). You should iterate over the length of jarray

Categories

Resources