how to pass header api key in volley - java

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

Related

Get POST Result in JSON

I'm sending the data with the POST. I get the answer with JSON.
If I use plain text instead of JSON, it's working but It doesn't work with JSON.
I do not receive any error screen in the application
if (status) = true -> Register OK
IMPORT:
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
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;
import java.util.HashMap;
import java.util.Map;
import javax.xml.transform.Result;
JSON:
[{"status":true,"result":"registerSuccessful","message":"Register succeeded"}]
JAVA Code:
private void registernewuser() {
StringRequest request = new StringRequest(Request.Method.POST, registerUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
String RegisterResultString = jsonResponse.getString("status");
if (RegisterResultString.equals("true")) {
Toast.makeText(getApplicationContext(), "Successfully Registered User", Toast.LENGTH_LONG).show();
Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "Sorry, Error Registering New User", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("registeruser", "true");
params.put("username", username.getText().toString().trim());
params.put("userpassword", userpassword.getText().toString().trim());
params.put("useremail", useremail.getText().toString());
return params;
}
};
Volley.newRequestQueue(this).add(request);
}
I'm not having trouble building applications. But I can't find my fault.
Your JSON code is a JSONArray with a single JSONObject because of square brackets. So, just set type of your jsonResponse as JSONArray and fetch a JSONObject using the JSONArray.getJSONObject(0) method.
JSONArray jsonResponse = new JSONArray(response);
String registerResultString = jsonResponse.getJSONObject(0).getString("status");
You need to add the header to your request to indicate the JSON usage :
request.addHeader("content-type", "application/json");
Else it will interpret it as plain text.
You can call the request as JSONRequest
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
your_url, new com.android.volley.Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
};

How to freeze the code until we receive the response of volley request?

I am trying to call this method from another class; it should return true or false after checking user ID and password on the server.
It always returns false even if the login process is successful because it returns the default value false before i got the request response!
I made a lot of search before posting this question but there is no clear answer on how to solve this problem.
MyHelper myHelper = new MyHelper();
myHelper.setVolleyResponseListener(new MyHelper.OnVolleyResponse()
{
#Override
public void onResponse(JSONObject jsonObject)
{
// do watever you want here with response.
}
});
if (myHelper.doBackgroundLogin(getApplicationContext())) {
uploadImageToServer();
}else{
finish();
startActivity(new Intent(AccountProfileImageActivity.this, AccountLoginActivity.class));
}
package com.company.testApp;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
/**
* Created by Aly on 1/11/2017.
*/
public class MyHelper {
private static AlertDialog.Builder builder;
public static Context ctx;
public static ValuesManager vm;
public static boolean status = false;
public static boolean doBackgroundLogin(final Context context) {
vm = new ValuesManager( context, context.getString(R.string.saved_values_file_name) );
String user_email = vm.retrieveSharedPreferences("user_email");
String user_password = vm.retrieveSharedPreferences("user_password");
Toast.makeText(context, user_email + " - " + user_password, Toast.LENGTH_SHORT).show();
//------------------------------------------------------------------------------------------
// final MyProgressDialog progressDialog;
// progressDialog = MyProgressDialog.show(context, "title", "message");
// //------------------------------------------------------------------------------------------
String url = context.getString(R.string.server_path);
Log.d("URL : ", url);
StringRequest stringRequest = new StringRequest(Request.Method.POST,
url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("response : ", response); // log the error to trace it and print message to user
// progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
JSONObject JO = jsonArray.getJSONObject(0);
String code = JO.getString("code");
if( code.equals("login_true") ) {
status = true;
vm.saveSharedPreferences( "user_token", JO.getString("user_token") );
Log.d("trace","code = " + code);
Log.d("trace","statusUpdated = " + status);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("vERROR : ", error.toString()); // log the error to trace it and print message to user
// progressDialog.dismiss();
}
}
)
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("action","account_login");
params.put("email_address",vm.retrieveSharedPreferences("user_email"));
params.put("password",vm.retrieveSharedPreferences("user_password"));
return params;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
100000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
MySingleton.getInstance(context).addToRequestQueue(stringRequest);
//------------------------------------------------------------------------------------------
Log.d("trace","status = " + status);
return status;
}
public interface OnVolleyResponse
{
void onResponse(JSONObject jsonObject);
}
public void setVolleyResponseListener(OnVolleyResponse responseListener)
{
this.volleyResponse = volleyResponse;
}
}
You have to use interface callback for this.
Why?
Because this is asynchronous call, and work on different thread. so your Main Thread will not wait for result of it.
Solution
Create interface in your MyHelper class
Edit
OnVolleyResponse onVolleyResponse;
public interface OnVolleyResponse
{
void onResponse(JSONObject jsonObject);
}
Create setter method for callback
public void setVolleyResponseListener(OnVolleyResponse responseListener)
{
this.volleyResponse = volleyResponse;
}
Now call this method from your Activity
MyHelper myHelper = new MyHelper();
myHelper.setVolleyResponseListener(new OnVolleyResponse()
{
#Override
public void onResponse(JSONObject jsonObject)
{
// do watever you want here with response.
}
});
if (myHelper.doBackgroundLogin(getApplicationContext())) {
uploadImageToServer();
}else{
finish();
startActivity(new Intent(AccountProfileImageActivity.this, AccountLoginActivity.class));
}
Note
Remove static from doBackgroundLogin method, and call it with instance of MyHelper.
Make an interface
public interface VolleyCallback{
public void onSuccess(boolean status);}
After this when you get a response you should change your doBackgroundLogin() method like this.
public static boolean doBackgroundLogin(final Context context,VolleyCallback callback) {
vm = new ValuesManager( context, context.getString(R.string.saved_values_file_name) );
String user_email = vm.retrieveSharedPreferences("user_email");
String user_password = vm.retrieveSharedPreferences("user_password");
Toast.makeText(context, user_email + " - " + user_password, Toast.LENGTH_SHORT).show();
String url = context.getString(R.string.server_path);
Log.d("URL : ", url);
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("response : ", response); // log the error to trace it and print message to user
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
JSONObject JO = jsonArray.getJSONObject(0);
String code = JO.getString("code");
if( code.equals("login_true") ) {
status = true;
vm.saveSharedPreferences( "user_token", JO.getString("user_token") );
Log.d("trace","code = " + code);
Log.d("trace","statusUpdated = " + status);
callback.onSuccess(status);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("vERROR : ", error.toString()); // log the error to trace it and print message to user
}
}
)
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("action","account_login");
params.put("email_address",vm.retrieveSharedPreferences("user_email"));
params.put("password",vm.retrieveSharedPreferences("user_password"));
return params;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
100000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
MySingleton.getInstance(context).addToRequestQueue(stringRequest);
Log.d("trace","status = " + status);
return status; }
Just see this callback.onSuccess(status);
This would send the response as soon as the login is successful.
onResponse method is for you volley handle this waiting for you and call onResponse method after fetching data or response from specific url.
final TextView mTextView = (TextView) findViewById(R.id.text);
...
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
mTextView.setText("Response is: "+ response.substring(0,500));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mTextView.setText("That didn't work!");
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);

return data from method (JSON Array)

I have one method with this url:
String url = "http://brunos.000webhostapp.com/teste/obter_id.php?descricao=" + value;
And i want to return the result of this method.
i have tried the VolleyCallback callback but i cant send the value to the method
package com.example.fabio.domoticaa;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.EditText;
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.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Divi_Dispo extends AppCompatActivity {
String x;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_divi__dispo);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final String[] count = new String[1];
final String[] id = new String[1];
Intent intent = getIntent();
String value = intent.getStringExtra("divisao");
final EditText nomediv = (EditText) findViewById(R.id.editText4);
Count(value);
nomediv.setText(x);//want set th result of Count(value)
}
public void Count(String value) {
final String[] count = new String[1];
// Send data
try {
RequestQueue queue = Volley.newRequestQueue(Divi_Dispo.this);
String url = "http://brunos.000webhostapp.com/teste/obter_id.php?descricao=" + value ;
JsonArrayRequest jsonRequest = new JsonArrayRequest
(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
JSONObject jObj = new JSONObject(String.valueOf(response.get(0)));
count[0] = jObj.getString("COUNT(id)");//want return this valor
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
queue.add(jsonRequest);
} catch (Exception ex) {
} finally {
}
}
public interface VolleyCallback {
void onSuccess(String result);
}
}

How can i declare all the brand's id globally and pass it as a parameter in http request using shared preference?

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

Android - Post image within json object to server using volley library

I want post json object included image to my server using Volley Library it post empty fields to server , image file posted successfully
I should post Json in this formate
{ "user_id":"value" , "post_title":"value","Specialty":"value","post_detail":"value", "uploaded_file","file" }
here is my android code
import android.util.Log;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.HttpHeaderParser;
import com.imaadv.leaynik.Util.AppConstants;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* Created by NT on 10/26/15.
*/
public class PhotoMultipartRequest<T> extends Request<T> {
private MultipartEntityBuilder mBuilder = MultipartEntityBuilder.create();
private Response.Listener<T> mListener;
private File mImageFile;
protected Map<String, String> headers;
private JSONObject params;
private String file_name;
private boolean hasFile;
public PhotoMultipartRequest(JSONObject params, String url, Response.ErrorListener errorListener, Response.Listener<T> listener, String file_name, File imageFile, boolean hasFile) {
super(Method.POST, url, errorListener);
mListener = listener;
mImageFile = imageFile;
this.params = params;
this.file_name = file_name;
this.hasFile = hasFile;
BuildMultiPartEntity();
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null || headers.equals(Collections.emptyMap())) {
headers = new HashMap<>();
}
headers.put("accept", "application/json");
headers.put("Content-type","application/json");
return headers;
}
private void BuildMultiPartEntity() {
// Set keys = params.keySet();
// for (Iterator i = keys.iterator(); i.hasNext(); ) {
// String key = (String) i.next();
// try {
//
// }catch (Exception e){
// e.printStackTrace();
// }
//
// }
StringBody userId = new StringBody(params.get(AppConstants.USER_ID) ,ContentType.APPLICATION_JSON);
StringBody postDetail = new StringBody(params.get(AppConstants.POST_DETAIL) ,ContentType.APPLICATION_JSON);
StringBody postTitle = new StringBody(params.get(AppConstants.POST_TITLE) ,ContentType.APPLICATION_JSON);
StringBody Speciality = new StringBody(params.get(AppConstants.SPECIALTY) ,ContentType.APPLICATION_JSON);
mBuilder.addPart(AppConstants.USER_ID ,userId );
mBuilder.addPart(AppConstants.POST_DETAIL ,postDetail );
mBuilder.addPart(AppConstants.POST_TITLE ,postTitle );
mBuilder.addPart(AppConstants.SPECIALTY ,Speciality );
mBuilder.addTextBody(AppConstants.DATA, params.toString());
if (hasFile) {
mBuilder.addBinaryBody(file_name, mImageFile, ContentType.create("image/jpeg"), mImageFile.getName());
}
mBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
mBuilder.setLaxMode().setBoundary("xx").setCharset(Charset.forName("UTF-8"));
}
#Override
public String getBodyContentType() {
String contentTypeHeader = mBuilder.build().getContentType().getValue();
return contentTypeHeader;
}
#Override
public byte[] getBody() throws AuthFailureError {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
mBuilder.build().writeTo(bos);
} catch (IOException e) {
VolleyLog.e("IOException writing to ByteArrayOutputStream bos, building the multipart request.");
}
return bos.toByteArray();
}
#Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
T result = null;
return Response.success(result, HttpHeaderParser.parseCacheHeaders(response));
}
#Override
protected void deliverResponse(T response) {
mListener.onResponse(response);
}
#Override
protected VolleyError parseNetworkError(VolleyError volleyError) {
Log.i("Error1", volleyError.getMessage());
return super.parseNetworkError(volleyError);
}
#Override
public void deliverError(VolleyError error) {
Log.i("Error2", error.getMessage());
super.deliverError(error);
}
}
Could any one guide me what is wrong in my code
You can see your answer on follow this 3 link.....
Click here
http://www.survivingwithandroid.com/2013/05/android-http-downlod-upload-multipart.html
http://www.androidhive.info/2014/05/android-working-with-volley-library-1/
https://www.simplifiedcoding.net/android-volley-tutorial-to-upload-image-to-server/
Best Luck..

Categories