This is my code...
b2 = (Button) findViewById(R.id.button3);
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getResults();
StringRequest request= new StringRequest(Request.Method.POST, server_url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
protected Map<String,String>getParams() throws AuthFailureError{
Map<String,String> parameters = new HashMap<String, String>();
getResults().put(parameters);
return parameters;
}
};
requestQueue.add(request);
}
});
}
private JSONArray getResults() {
String myPath = "/data/data/com.example.sebastian.patientdetails/databases/" + "MyDBName.db";
String myTable = "patients";
SQLiteDatabase myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
String searchQuery = "SELECT * FROM " + myTable;
Cursor cursor = myDataBase.rawQuery(searchQuery, null);
JSONArray resultSet = new JSONArray();
cursor.moveToFirst();
JSONArray jsonArray = null;
while (!cursor.isAfterLast()) {
int totalColumn = cursor.getColumnCount();
JSONObject rowObject = new JSONObject();
//new jsonarray
jsonArray = new JSONArray();
for (int i = 0; i < totalColumn; i++) {
if (cursor.getColumnName(i) != null) {
//new jsonarray of items jsonObject
JSONObject object = new JSONObject();
try {
if (cursor.getString(i) != null) {
Log.d("TAG_NAME", cursor.getString(i));
object.put(cursor.getColumnName(i), cursor.getString(i));
} else {
object.put(cursor.getColumnName(i), "");
}
//put jsonarray
jsonArray.put(object);
} catch (Exception e) {
Log.d("TAG_NAME", e.getMessage());
}
}
}
//put request jsonobject
jsonArray.put(rowObject);
resultSet.put(rowObject);
cursor.moveToNext();
}
return jsonArray;
}
}
When i click the button to sent my json object to server i got this error ' Unexpected response code 500 ' . Whats the reason. How can i fix this issue. Is there any issue in converting my sqlite to json object.?
The Web server (running the Web Site) encountered an unexpected condition that prevented it from fulfilling the request by the client (e.g. your Web browser or our CheckUpDown robot) for access to the requested URL.
This is a 'catch-all' error generated by the Web server. Basically something has gone wrong, but the server can not be more specific about the error condition in its response to the client. In addition to the 500 error notified back to the client, the Web server should generate some kind of internal error log which gives more details of what went wrong. It is up to the operators of the Web server site to locate and analyse these logs.
reference: http://www.checkupdown.com/status/E500.html
Related
I am getting data on splash. I have almost 7k data that I am getting from the server. While getting data from the server I am saving it in the local database but the problem is the process is too slow. It almost takes 5 minutes. I want to resolve the problem. Please help.
Code to get data from server and save it into database:
private void productsDetailsApi() {
String tag_json_obj = "json_obj_req";
String url = Constants.PRODUCTS_DETAILS_URL;
pBar.setVisibility(View.VISIBLE);
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, new JSONObject(),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e("product_response", response.toString());
try {
JSONArray jsonArray = response.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
JSONObject company = jsonObject.getJSONObject("company");
ModelProductDetail modelProductDetail = new ModelProductDetail();
modelProductDetail.setCompany_id(jsonObject.getString("company_id"));
modelProductDetail.setProduct_name_nl(jsonObject.getString("name_nl"));
modelProductDetail.setProduct_name_fr(jsonObject.getString("name_fr"));
modelProductDetail.setProduct_desc(jsonObject.getString("description"));
modelProductDetail.setProduct_id(jsonObject.getString("id"));
modelProductDetail.setEan_code(jsonObject.getString("ean_code").trim());
modelProductDetail.setArticle_code(jsonObject.getString("article_code").trim());
modelProductDetail.setProduct_mbh(jsonObject.getString("mbh"));
modelProductDetail.setProduct_msrp(jsonObject.getString("msrp"));
modelProductDetail.setProduct_source(jsonObject.getString("source"));
modelProductDetail.setCompany_name(company.getString("name"));
modelProductDetail.setFranco_trading_value("");
modelProductDetail.setFranco_product_value(company.getString("franco_amount_product"));
dbHelper.addProductsDetails(modelProductDetail);
}
dbHelper.close();
ArrayList<ModelProductDetail> modelProductCodeList = dbHelper.getProductsArticleCode();
Log.e("TAG", "ModelProductDetail:art " + modelProductCodeList.size());
shopDetailsApi();
} catch (Exception e) {
e.printStackTrace();
}
//pBar.setVisibility(View.GONE);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: " + error.getMessage());
// pBar.setVisibility(View.GONE);
}
});
jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(
100000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
}
Databse Insert Query
//add products data
public void addProductsDetails(ModelProductDetail modelProductDetail) {
SQLiteDatabase productsDb = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_PRODUCT_ID, modelProductDetail.getProduct_id());
values.put(KEY_PRODUCT_NAME_FR, modelProductDetail.getProduct_name_fr());
values.put(KEY_PRODUCT_NAME_NL, modelProductDetail.getProduct_name_nl());
values.put(KEY_PRODUCT_DESC, modelProductDetail.getProduct_desc());
values.put(KEY_PRODUCT_ART, modelProductDetail.getArticle_code());
values.put(KEY_PRODUCT_EAN, modelProductDetail.getEan_code());
values.put(KEY_PRODUCT_MBH, modelProductDetail.getProduct_mbh());
values.put(KEY_PRODUCT_MSRP, modelProductDetail.getProduct_msrp());
values.put(KEY_PRODUCT_SOURCE, modelProductDetail.getProduct_source());
values.put(KEY_COMPANY_ID, modelProductDetail.getCompany_id());
values.put(KEY_COMPANY_NAME, modelProductDetail.getCompany_name());
values.put(KEY_FRANCO_TRADING, modelProductDetail.getFranco_trading_value());
values.put(KEY_FRANCO_PRODUCT, modelProductDetail.getFranco_product_value());
productsDb.insert(TABLE_PRODUCT_DETAILS, null, values);
productsDb.close();
}
You could try wrapping all the inserts inside a transaction e.g. :-
JSONArray jsonArray = response.getJSONArray("data");
dbHelper.getWritableDatabase.beginTransaction(); //<<<<<<<<<< ADDED
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
JSONObject company = jsonObject.getJSONObject("company");
ModelProductDetail modelProductDetail = new ModelProductDetail();
modelProductDetail.setCompany_id(jsonObject.getString("company_id"));
modelProductDetail.setProduct_name_nl(jsonObject.getString("name_nl"));
modelProductDetail.setProduct_name_fr(jsonObject.getString("name_fr"));
modelProductDetail.setProduct_desc(jsonObject.getString("description"));
modelProductDetail.setProduct_id(jsonObject.getString("id"));
modelProductDetail.setEan_code(jsonObject.getString("ean_code").trim());
modelProductDetail.setArticle_code(jsonObject.getString("article_code").trim());
modelProductDetail.setProduct_mbh(jsonObject.getString("mbh"));
modelProductDetail.setProduct_msrp(jsonObject.getString("msrp"));
modelProductDetail.setProduct_source(jsonObject.getString("source"));
modelProductDetail.setCompany_name(company.getString("name"));
modelProductDetail.setFranco_trading_value("");
modelProductDetail.setFranco_product_value(company.getString("franco_amount_product"));
dbHelper.addProductsDetails(modelProductDetail);
}
dbHelper.getWritableDatabase.setTransactionSuccessful(); //<<<<<<<<<< ADDED
dbHelper.getWritableDatabase.endTransaction(); //<<<<<<<<<< ADDED
dbHelper.close();
To use the above you would also have to remove the line
productsDb.close();
From the Insert Query
I've been trying for a while now to convert all my phone numbers in my phone to JSON and upload them in one post to a mysql db, can you help? I'm focusing on the Android side of things right now - php will be later.
So, I make an arraylist of all my numbers - when you click the buttonCheck button you can see them all in logcat, but after all I've read the methods size and length are still not recognised by my alContacts array. I believe that's the track I should be taking to convert to JSON (?). Here's my code :
public class MainActivity extends AppCompatActivity {
// this is the php file name where to select from the database, the user's phone number
private static final String CHECKPHONENUMBER_URL = "http://www.example.com/myfile.php";
//we are posting phoneNo, which in PHP is phonenumber
public static final String KEY_PHONENUMBER = "phonenumber";
//alContacts is a list of all the phone numbers
public static final ArrayList<String> alContacts = new ArrayList<String>();
Button buttonCheck;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonCheck = (Button) findViewById(R.id.buttonCheck);
//get the names and phone numbers of all contacts in phone book
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(
cur.getColumnIndex(ContactsContract.Contacts._ID));
if (cur.getInt(cur.getColumnIndex(
ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
String phoneNo = pCur.getString(pCur.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
alContacts.add(phoneNo);
// break;
}
pCur.close();
}
}
}
buttonCheck.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
System.out.println("Print the contacts array : ");
System.out.println(alContacts);
CheckifUserisContact();
}
});
}
// send the numbers in one POST to the mySql db with Volley
private void CheckifUserisContact() {
StringRequest stringRequest = new StringRequest(Request.Method.POST, CHECKPHONENUMBER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.equals("failure")) {
Toast.makeText(MainActivity.this, "failed", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "succeeded", Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
//********* HAVING TROUBLE HERE *******************
// JSONObject jsonObject=new JSONObject();
JSONArray jsonArray = new JSONArray();
// jsonObject.put("alContacts",jsonArray);
//for(int i=0;i<=alContacts.size;i++){}
//*****************************************************
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put(KEY_PHONENUMBER, jsonArray.toString());
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
Try this:
//********* HAVING TROUBLE HERE *******************
try {
JSONObject dataToSend = new JSONObject();
// contacts
JSONArray jsonArrayContacts = new JSONArray();
for (int i = 0; i < alContacts.size(); i++)
{
// contact
JSONObject jsonObjectContact = new JSONObject();
jsonObjectContact.put("phone_number", alContacts.get(i));
// Add contact jsonObject to contacts jsonArray
jsonArrayContacts.put(jsonObjectContact);
}
// Add contacts jsonArray to jsonObject
dataToSend.put("contacts", jsonArrayContacts);
Log.d("JSON", "JSON: " + dataToSend.toString());
} catch (final JSONException e) {
Log.e("FAILED", "Json parsing error: " + e.getMessage());
}
//*****************************************************
Here is the output JSON format:
{
"contacts":[
{
"phone_number":"019114-123456"
},
{
"phone_number":"016174-123456"
},
{
"phone_number":"012104-123456"
}]
}
Hope this will help~
Questions Description:
I Have four methode to get all the data of related things from server:
BankList();
BranchList();
StateDetails();
DistrictDetails();
In that I am fetching data From Server related with Bank Details one by one using Volley .and Storing into SQLite.
Quetions:
Please Check below Code
What is Correct way to call volley String Request one by one.
How to call volley String request one by One on Priority or automatically.
Code is Working Fine and its storing value into SQLite Also.
But Loader Progress Dialog not working Properly . its freezing the app its not working properly .it gives me output but application freeze for few second if network speed is slow like 3G then it took more time and then my application will freeze for more time . so please help me how to avoid that
My Question is My way is correct or wrong. how to call methods one after another . on priority basis or automatically one by one
Please Check below Code
public class LoginPage extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_page);
BankList();
BranchList();
StateDetails();
DistrictDetails();
}
public void BankList() {
final ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Fetching Data");
pDialog.setCancelable(false);
pDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST,
BankURL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
pDialog.hide();
result = response;
Log.e("Responce is ", result);
File dbtest = new File(Utils.DB_PATH + Utils.DB_NAME);
if (dbtest.exists()) {
Log.e("db create", "Databse is Created");
String myPath = DB_PATH + DB_NAME;
SQLiteDatabase db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
db.delete("BankList", null, null);
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i <= jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int BankID = jsonObject.getInt("BankID");
String BankName = jsonObject.getString("BankName");
Log.e("Bank ID", String.valueOf(BankID));
Log.e("Bank Name", BankName);
ContentValues cv = new ContentValues();
cv.put("BankID", BankID);
cv.put("BankName", BankName);
db.insert("BankList", null, cv);
}
} catch (Exception e) {
}
} else {
Log.e("db Not created ", "Just Inserted Value");
SQLDatabase so = new SQLDatabase(getApplicationContext(), DB_NAME, null, 1);
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i <= jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int BankID = jsonObject.getInt("BankID");
String BankName = jsonObject.getString("BankName");
Log.e("Bank ID", String.valueOf(BankID));
Log.e("Bank Name", BankName);
so.BankList(BankID, BankName);
}
} catch (Exception e) {
}
}
}
}
, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
pDialog.hide();
}
}
)
{
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("getdata", "BankList");
return params;
}
};
// Adding request to request queue
VolleyAppController.getInstance().
addToRequestQueue(stringRequest);
}
public void StateDetails() {
final ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Fetching Data");
pDialog.setCancelable(false);
pDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST,
BankURL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
pDialog.hide();
result = response;
Log.e("Responce is ", result);
File dbtest = new File(Utils.DB_PATH + Utils.DB_NAME);
if (dbtest.exists()) {
Log.e("db create", "Databse is Created");
String myPath = DB_PATH + DB_NAME;
SQLiteDatabase db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
db.delete("StateList", null, null);
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i <= jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int StateID = jsonObject.getInt("StateID");
String StateName = jsonObject.getString("StateName");
int Bank_id = jsonObject.getInt("Bank_id");
ContentValues cv = new ContentValues();
cv.put("StateID", StateID);
cv.put("StateName", StateName);
cv.put("Bank_id", Bank_id);
db.insert("StateList", null, cv);
}
} catch (Exception e) {
}
} else {
Log.e("db Not created ", "Just Inserted Value");
SQLDatabase so = new SQLDatabase(getApplicationContext(), DB_NAME, null, 1);
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i <= jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int stateId = jsonObject.getInt("StateID");
String stateName = jsonObject.getString("StateName");
int bankID = jsonObject.getInt("Bank_id");
so.StateList(stateId, stateName, bankID);
}
} catch (Exception e) {
}
}
}
}
, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
pDialog.hide();
}
}
)
{
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("getdata", "StateList");
return params;
}
};
// Adding request to request queue
VolleyAppController.getInstance().
addToRequestQueue(stringRequest);
}
public void DistrictDetails() {
final ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Fetching Data");
pDialog.setCancelable(false);
pDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST,
BankURL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
pDialog.hide();
result = response;
Log.e("Responce is ", result);
File dbtest = new File(Utils.DB_PATH + Utils.DB_NAME);
if (dbtest.exists()) {
Log.e("db create", "Databse is Created");
String myPath = DB_PATH + DB_NAME;
SQLiteDatabase db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
db.delete("DistrictList", null, null);
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i <= jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int DistrictId = jsonObject.getInt("DistrictId");
String DistrictName = jsonObject.getString("DistrictName");
int StateID = jsonObject.getInt("StateID");
ContentValues cv = new ContentValues();
cv.put("DistrictId", DistrictId);
cv.put("DistrictName", DistrictName);
cv.put("StateID", StateID);
db.insert("DistrictList", null, cv);
}
} catch (Exception e) {
}
} else {
Log.e("db Not created ", "Just Inserted Value");
SQLDatabase so = new SQLDatabase(getApplicationContext(), DB_NAME, null, 1);
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i <= jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int DistrictId = jsonObject.getInt("DistrictId");
String DistrictName = jsonObject.getString("DistrictName");
int StateID = jsonObject.getInt("StateID");
so.DistrictList(DistrictId, DistrictName, StateID);
}
} catch (Exception e) {
}
}
}
}
, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
pDialog.hide();
}
}
)
{
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("getdata", "DistrictList");
return params;
}
};
// Adding request to request queue
VolleyAppController.getInstance().
addToRequestQueue(stringRequest);
}
public void BranchList() {
final ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Fetching Data");
pDialog.setCancelable(false);
pDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST,
BankURL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
pDialog.hide();
result = response;
Log.e("Responce is ", result);
File dbtest = new File(Utils.DB_PATH + Utils.DB_NAME);
if (dbtest.exists()) {
Log.e("db create", "Databse is Created");
String myPath = DB_PATH + DB_NAME;
SQLiteDatabase db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
db.delete("BranchList", null, null);
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i <= jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int BranchID = jsonObject.getInt("BranchID");
String BranchName = jsonObject.getString("BranchName");
String IFSC_code = jsonObject.getString("IFSC_code");
int District_id = jsonObject.getInt("District_id");
ContentValues cv = new ContentValues();
cv.put("BranchID", BranchID);
cv.put("BranchName", BranchName);
cv.put("IFSC_code", IFSC_code);
cv.put("District_id", District_id);
db.insert("BranchList", null, cv);
}
} catch (Exception e) {
}
} else {
Log.e("db Not created ", "Just Inserted Value");
SQLDatabase so = new SQLDatabase(getApplicationContext(), DB_NAME, null, 1);
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i <= jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int BranchID = jsonObject.getInt("BranchID");
String BranchName = jsonObject.getString("BranchName");
String IFSC_code = jsonObject.getString("IFSC_code");
int District_id = jsonObject.getInt("District_id");
so.BranchList(BranchID, BranchName, IFSC_code, District_id);
}
} catch (Exception e) {
}
}
}
}
, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
pDialog.hide();
}
}
)
{
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("getdata", "BranchList");
return params;
}
};
// Adding request to request queue
VolleyAppController.getInstance().addToRequestQueue(stringRequest);
}
}
There is problem with your code. The volley onResponse() and onErrorResponse() methods are always invoked in the main UI thread. In your code you place the SQLite database write operation inside the volley onResponse() method. The database write operation may be a long running process depending on the size of the data.
In your code the main UI thread sleep and wait for the database write operation to finish, and this is why your application user interface freeze. Place the database write operation on a separate background thread will solve your problem.
Use AsyncTask for the write operation.
This code is supposed to be sending my JSON value to the server. When I click the button, I get an error - Unexpected reponse code 404.
Could someone explain what the problem is and how I can solve it?
Is this a server side error?
This is my code...
b2.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
getResults();
StringRequest request=new StringRequest(Request.Method.POST,server_url,new Response.Listener<String>() {
#Override
public void onResponse(String response){
}
},new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error) {
}
})
{
protected Map<String,String>getParams() throws AuthFailureError{
Map<String,String> parameters = new HashMap<String, String>();
getResults().put(parameters);
return parameters;
}
};
requestQueue.add(request);
}
});
}
private JSONArray getResults() {
String myPath = "/data/data/com.example.sebastian.patientdetails/databases/" + "MyDBName.db";
String myTable = "patients";
SQLiteDatabase myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
String searchQuery = "SELECT * FROM " + myTable;
Cursor cursor = myDataBase.rawQuery(searchQuery, null);
JSONArray resultSet = new JSONArray();
cursor.moveToFirst();
JSONArray jsonArray = null;
while (!cursor.isAfterLast()) {
int totalColumn = cursor.getColumnCount();
JSONObject rowObject = new JSONObject();
jsonArray = new JSONArray();
for (int i = 0; i < totalColumn; i++) {
if (cursor.getColumnName(i) != null) {
JSONObject object = new JSONObject();
try {
if (cursor.getString(i) != null) {
Log.d("TAG_NAME", cursor.getString(i));
object.put(cursor.getColumnName(i), cursor.getString(i));
} else {
object.put(cursor.getColumnName(i), "");
}
jsonArray.put(object);
}
catch (Exception e) {
Log.d("TAG_NAME", e.getMessage());
}
}
}
jsonArray.put(rowObject);
resultSet.put(rowObject);
cursor.moveToNext();
}
return resultSet;
}
}
404 means not found, server_url points to a not existent URL or the page you are requesting is redirecting you to 404.
If you open a browser and send a POST request in AJAX to the same URL and the same parameters, then you should experience the same behavior.
I got this error...
10-27 12:07:08.101 10065-10108/com.example.sebastian.patientdetails D/TAG_NAME: [{"_id":"1","name":"Sss","dob":"10\/1\/2000","gender":"Male","mobile":"1234567890","address":"asdasd"}]
10-27 12:07:08.102 10065-10108/com.example.sebastian.patientdetails E/Volley: [141] NetworkDispatcher.run: Unhandled exception java.lang.ClassCastException: org.json.JSONArray cannot be cast to java.util.Map
java.lang.ClassCastException: org.json.JSONArray cannot be cast to java.util.Map
at com.example.sebastian.patientdetails.MainActivity$3$3.getParams(MainActivity.java:112)
at com.android.volley.Request.getBody(Request.java:460)
at com.android.volley.toolbox.HurlStack.addBodyIfExists(HurlStack.java:253)
at com.android.volley.toolbox.HurlStack.setConnectionParametersForRequest(HurlStack.java:227)
at com.android.volley.toolbox.HurlStack.performRequest(HurlStack.java:107)
at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:97)
at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:114)
I need to sent my json array to a server url. When i click the button i got this error. Can anyody suggest me whats the error means.? Can anybody suggest me a good tutorial for json to server inserting.?
MainActivity Code...
...
b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), AddPatient.class);
startActivity(i);
}
});
b2 = (Button) findViewById(R.id.button3);
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getResults();
StringRequest request=new StringRequest(Request.Method.POST, server_url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
protected Map<String,String>getParams()throws AuthFailureError {
Map<String,String> parameters= new HashMap<String, String>();
return (Map<String, String>) getResults();
}
};
requestQueue.add(request);
}
});
}
private JSONArray getResults() {
String myPath = "/data/data/com.example.sebastian.patientdetails/databases/" + "MyDBName.db";
String myTable = "patients";
SQLiteDatabase myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
String searchQuery = "SELECT * FROM " + myTable;
Cursor cursor = myDataBase.rawQuery(searchQuery, null);
JSONArray resultSet = new JSONArray();
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
int totalColumn = cursor.getColumnCount();
JSONObject rowObject = new JSONObject();
for (int i = 0; i < totalColumn; i++) {
if (cursor.getColumnName(i) != null) {
try {
if (cursor.getString(i) != null) {
Log.d("TAG_NAME", cursor.getString(i));
rowObject.put(cursor.getColumnName(i), cursor.getString(i));
} else {
rowObject.put(cursor.getColumnName(i), "");
}
} catch (Exception e) {
Log.d("TAG_NAME", e.getMessage());
}
}
}
resultSet.put(rowObject);
cursor.moveToNext();
}
cursor.close();
Log.d("TAG_NAME", resultSet.toString());
return resultSet;
}
You cannot convert JSONArray to Map , but you can convert JSONObject to Map and can get value by keys.
First get JSONObject from the JSONArray and convert it to Map.
you cannot convert JSONArray cannot be cast to java.util.Map
you should found some solution on stack overflow related your error
reference link please Visit this answer
import java.lang.reflect.Type;
import com.google.gson.reflect.TypeToken;
// ...
Type listType = new TypeToken<List<String>>() {}.getType();
List<String> yourList = new Gson().fromJson(jsonResponce, listType);