Click here to Skip to main content
16,017,245 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello friends, i need to pass the all brand's id dynamically as al parameter while adding a vehicle in my main Activity using BasicNameValuePair, so that it should change dynamically according to the user selection in the spinner and it should show the output of the added vehicle on another activity,Kindly help me.

Herewith in this post, i have attached my API response which contains brand ids for all the 5 brands. I have also attached my mainActivity.

What I have tried:

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"
}

And i need to declare all the brand's id under one global variable and i need to pass that global variable as a parameter value for brand while adding the vehicle using BasicNameValuePair as shown below:

My MainActivity:

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","1"));
nameValuePair.add(new BasicNameValuePair("model", "1"));
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);


}
}
}



As you see in my above code, I have passed only one value for the brand,So that it shows only one brand id (1) in my output, but i need all the 5 brand ids to pass dynamically so that the user can select the desired one via spinner, so that it shows what the user has selected.

Shortly saying, I need to declare all the 5 brand ids under the global variable,and i need to pass the global variable as a parameter for adding the brand using basicnamevaluepair,

Sorry for long explaination., please suggest me a good solution, Thanks in advance.
Posted
Updated 4-Jan-17 0:35am
v3
Comments
Richard MacCutchan 4-Jan-17 6:10am    
Why are you using namevaluepair and not a properly defined class to hold all the details of each car?
Arun Theandroider 4-Jan-17 6:27am    
Hi Richard, I have just posted only the adding part of the vehicle, I didn't posted my full java class, If you need let me post that too
Please find my mainActivity in my edited post
Richard MacCutchan 4-Jan-17 6:39am    
I repeat, why are you not using a proper class?
Arun Theandroider 4-Jan-17 6:45am    
ok Richard, you please say me how can i modify this class to a proper class?
Richard MacCutchan 4-Jan-17 7:08am    
Are you saying that you do not know how to create classes in Java?

Also, please do not just dump all your code in an unformatted list. Use <pre> tags and post only the code that is relevant to your query.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900