I'm using Volley to interact with an API. I need to send a post request (with parameters) to a service that returns a JSON Array.
My Api code is having a function like:
public function Add($tripData) {
$response = "Unsuccessful";
if (isset($tripData)) {
//print_r($tripData);
$tripsModel = new TasksModel();
$tripsModel->user_id = $tripData["user_id"];
$tripsModel->date = $tripData["date"];
$tripsModel->latitude = $tripData["latitude"];
$tripsModel->longitude = $tripData["longitude"];
$tripsModel->location = $tripData["location"];
$tripsModel->notes = $tripData["notes"];
$tripsModel->trip = $tripData["trip"];
$tripsModel->city = $tripData["city"];
$method = new CommonMethods();
$response = $method->save("locationdetails", $tripsModel);
}
echo json_encode($response);
}
I just need to put params.put("data", data) to be in following kind of array:
$taskData["user_id"]=2;
$tripData["date"]="2015-06-02 16:01";
$tripData["latitude"]="41.213181";
$tripData["longitude"]="-124.004631";
$tripData["location"]="Redwood National";
$tripData["notes"]="hello";
$tripData["trip"]=3;
$tripData["city"]="California";
so that it could be used as:
$obj = new Myclass;
$var = $obj->Add($tripData);
I have checked the service already but could not post it from android code using hashmap.
private void insertTripData(final String[] tripData) {
// TODO Auto-generated method stub
// Tag used to cancel the request
String tag_string_req = "req_login";
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("inserttrip",
"inserttrip Response: " + response.toString());
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
// user successfully logged in
// Create login session
// Launch main activity
Toast.makeText(getApplicationContext(),
"user data inserted", Toast.LENGTH_LONG)
.show();
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
// String errorMsg =
// "Please check your network connection";
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("insertTripError",
"Data Error: " + error.getMessage());
String errorMsg = "Please check your network connection";
Toast.makeText(getApplicationContext(), errorMsg,
Toast.LENGTH_LONG).show();
}
}) {
#Override
protected HashMap<String, String> getParams() {
// Posting parameters to login url
JSONObject jsonObject = new JSONObject();
for (int i = 0; i <= tripData.length; i++) {
tripData[i] = "questionId_" + i + "_" + "ans_" + i;
try {
jsonObject.put("params_" + i, tripData[i]);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String data= jsonObject.toString();
HashMap<String, String> params = new HashMap<String, String>();
params.put("tag", "trip");
params.put("action", "add");
params.put("data", data);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
You said, getting "ArrayIndexOutOfBound" error in your logcat.
May be problem with your getParams() method.
Change the for loop this:
for (int i = 0; i <= tripData.length; i++)
To:
for (int i = 0; i < tripData.length; i++)
Check now and if you get any other problem, please show your logcat here,.
Related
I am sending multiple request through for loop.
On response I get success or failure message, and I need to show this message in a AlertDialog.
My Problem is: when I am sending 10 request then I am getting 10 response hence 10 times dialogue is showing with response.
I want to show only one dialogue when all response will have come,and that dialogue should contain response according to their each and every request.
How can I do it.
code which I tried:
if (globalInstance.isNetworkAvailable(AddBookingList.this)) {
int si = checkedItems.size();
if (checkedItems.size() > 0) {
for (int i = 0; i < si; i++) {
int appid = checkedItems.get(i).getAppid();
int bookingId = checkedItems.get(i).getBookingid();
List<Contacts> con = db.getadvertisment(bookingId);
List<AddImages> img = db.getImagesbybookingId(bookingId);
String postXml = createxmlForPost(con, img);
sendDataToServer(postXml,appid, bookingId, si);
}
}
}
private void sendDataToServer(final String postXml, final int appid, final int bookingId, final int si) {
final ProgressDialog progressDialog = new ProgressDialog(this, R.style.AppCompatAlertDialogStyle);
progressDialog.setMessage("Please wait...");
progressDialog.setCancelable(false);
progressDialog.show();
try {
final RequestQueue queue = Volley.newRequestQueue(this);
JSONObject obj = new JSONObject();
obj.put("xmlData", postXml);
int socketTimeout = 30000;//30 seconds
final StringRequest postRequest = new StringRequest(Request.Method.POST, Constants.Rootpath + "PostBooking",
new Response.Listener<String>() {
#Override
public void onResponse(String st) {
if (progressDialog != null || progressDialog.isShowing()) {
progressDialog.dismiss();
}
try {
JSONArray response = new JSONArray(st);
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
int status = jsonObject.getInt("Status");
String msg = jsonObject.getString("Msg");
String serverbooking_id = jsonObject.getString("BookingId");
if (status == 1) {
checkedItems.clear();
if (response.length() > 1) {
String newserverbooking_id = response.getJSONObject(0).getString("BookingId") + "\n" + response.getJSONObject(1).getString("BookingId");
db.updateBookingDetailsbyAppId(newserverbooking_id, appid, status);
} else {
db.updateBookingDetailsbyAppId(serverbooking_id, appid, status);
}
showDatainList();
globalInstance.showSuceessMessage(true, "Success!!! Your BookingID is: " + serverbooking_id, AddBookingList.this);
try {
List<Contacts> contacts = db.getAllBookingDetails();
for (int h = 0; h < contacts.size(); h++) {
locallySaveImagesinPhone(bookingId, contacts.get(h).get_serverbookingId());
}
} catch (IOException e) {
e.printStackTrace();
}
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
} else {
globalInstance.showFailureMessage(false, "Booking Failed." + msg, AddBookingList.this);
checkedItems.clear();
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (progressDialog != null || progressDialog.isShowing()) {
progressDialog.dismiss();
}
String msg = error.getMessage();
globalInstance.showFailureMessage(false, "Booking Failed.Please Try Again!!!", AddBookingList.this);
}
}
) {
#Override
protected Map<String, String> getParams() {
HashMap<String, String> params = new HashMap<>();
params.put("xmldata", postXml);
return params;
}
};
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
postRequest.setRetryPolicy(policy);
queue.add(postRequest);
} catch (JSONException e1) {
e1.printStackTrace();
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
As i understand your problem is calling globalInstance.showSuceessMessage() or globalInstance.showFailureMessage every time you get the response.
what i think might work is:
Instead of these two methods, define an Arraylist<String> and based on the
success or failure of the response add messages to it like "Success!!! Your BookingID is: " + serverbooking_id and "Booking Failed." + msg.
Define a method like showMessages() which has a dialogue containing the messages u added to arraylist before. then call it after where you called thesendDataToServer method which is in the if (checkedItems.size() > 0) block.
I have this method to get data from server using volley and store it into sqlite database using ormlite. I'm doing this on splash screen. so now I want to show some progressbar when this process happen, the progress bar already appear and now I want to set the progress of progress bar inside the for loop. But I dont know why my progress bar keep on 0% until the process finish. when I look at the log the progress keep update but maybe because it inside a loop the progress not appear. How can I make the progress appear in my progressdialog?? below is my code
private void fetchMOffice() {
mOfficeAdapter = new TableMOfficeAdapter(this);
List<TableMOffice> listOffice = mOfficeAdapter.getAllDatabyLup();
progressBar = new ProgressDialog(SplashScreenActivity.this);
progressBar.setCancelable(true);
progressBar.setMessage("Downloading File...");
progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressBar.setProgress(0);
progressBar.setMax(100);
showDialog();
for (int i=0; i<listOffice.size(); i++) {
TableMOffice item = listOffice.get(i);
lupMOffice = item.getLup();
// locationIdArray.add(item.getKode_office());
break;
}
Log.e(TAG, "lup fetchMOffice: " +lupMOffice );
StringRequest strReq = new StringRequest(Request.Method.POST,
ConnectionManager.MASTER_M_OFFICE, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e(TAG, "response: " + response);
try {
JSONObject obj = new JSONObject(response);
dbAdapter = new TableMOfficeAdapter(SplashScreenActivity.this);
// dbAdapter.deleteAll();
// SQLiteStatement insert = mDb.compileStatement(sql);
// check for error flag
if (obj.getBoolean("error") == false) {
jsonArray = obj.getJSONArray("m_office");
for ( i = 0; i < jsonArray.length(); i++) {
JSONObject versionObj = null;
versionObj = (JSONObject) jsonArray.get(i);
int id = versionObj.getInt("id");
String office = versionObj.getString("office");
String kode_office = versionObj.getString("kode_office");
String channel = versionObj.getString("channel");
String jenis = versionObj.getString("jenis");
String alamat = versionObj.getString("alamat");
String kota = versionObj.getString("kota");
String propinsi = versionObj.getString("propinsi");
String pic = versionObj.getString("pic");
String pic_phone = versionObj.getString("pic_phone");
String map_lat = versionObj.getString("map_lat");
String map_lng = versionObj.getString("map_lng");
String upd = versionObj.getString("upd");
String lup = versionObj.getString("lup");
String ket = versionObj.getString("ket");
String region = versionObj.getString("region");
String rek = versionObj.getString("rek");
String bank = versionObj.getString("bank");
String rental = versionObj.getString("rental");
Log.e("isitabeloffice", Integer.toString(id));
ctx = getApplicationContext();
dbAdapter.delete(SplashScreenActivity.this,id);
//dbAdapter.delete(ctx,id);
dbAdapter.insertData(new TableMOffice(), id, office, kode_office, channel,
jenis, alamat, kota, propinsi, pic, pic_phone, map_lat, map_lng,
upd, lup, ket, region, rek, bank, rental);
progress = (i+1)*100/jsonArray.length();
progressBar.setProgress(progress);
}
} else {
}
} catch (Exception e) {
Log.e(TAG, "json parsing error: " + e.getMessage());
//Toast.makeText(SplashScreenActivity.this, "Json parse error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
Log.e(TAG, "Volley error: " + error.getMessage() + ", code: " + networkResponse);
hideDialog();
//Toast.makeText(SplashScreenActivity.this, "Volley error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
Log.e(TAG, "params: " + params.toString());
return params;
}
};
MyApplication.getInstance().addToRequestQueue(strReq);
}
I'm posting "id" value (which i pass to this activity via getintent)
Uid = getIntent().getStringExtra("id");
to server and retrieving the corresponding jsonobjects.
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("id", Uid);
return params;
}
When my jsonarray is empty, my app crashes. I want to toast"Error" when jsonarray is empty. How can I fix this?
Here is my code:
public class kill extends FragmentActivity {
GridView grid1;
CustomGrid_Album adapter;
private ProgressDialog pDialog;
String Uid,Disp;
public String category;
public String selected;
public static String imagename;
Button Alb_sel;
ArrayList<Item_album> gridArray = new ArrayList<Item_album>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.album_display);
grid1 = (GridView) findViewById(R.id.gridView2);
Uid = getIntent().getStringExtra("id");
Disp = getIntent().getStringExtra("disp");
Alb_sel=(Button)findViewById(R.id.album_to_select);
pDialog = new ProgressDialog(kill.this);
pDialog.setMessage("Loading...");
pDialog.show();
//fetching JSONArray
final RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.POST, AppConfig.URL_Gallery4,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Datas.imageIds = new String[response.length()];
JSONArray arr = null;
try {
arr = new JSONArray(response);
} catch (JSONException e1) {
e1.printStackTrace();
}
int i=0;
for (i = 0; i < arr.length(); i++) {
try {
JSONObject obj = arr.getJSONObject(i);
category = obj.getString("category_name");
selected = obj.getString("album_id");
imagename = obj.getString("org_image_name");
Datas.imageIds[i] = AppConfig.URL_IMAGE_temp+obj.getString("album_image").substring(3);
gridArray.add(new Item_album(Datas.imageIds[i]));
} catch (JSONException e) {
e.printStackTrace();
}
}
final int xl = i;
adapter = new CustomGrid_Album(kill.this,xl,gridArray);
adapter.notifyDataSetChanged();
grid1.setAdapter(adapter);
pDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "No images in this gallery", Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
})
{
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("id", Uid);
return params;
}
};
queue.add(stringRequest);
}
}
apply the check in onResponse
if(response.length()==0){
// error message
}else{
// your rest of the code
}
This looks problematic.
Datas.imageIds = new String[response.length()];
You don't want an array with the size of the string. You want an array of the size of the JSONArray within the response.
public void onResponse(String response) {
JSONArray arr = null;
try {
arr = new JSONArray(response);
Datas.imageIds = new String[arr.length()];
} catch (JSONException e1) {
e1.printStackTrace();
}
However, your code is going to continue on if an exception is thrown there, then you'll end up with a NullPointerException, so you should move the for-loop into the try-catch as well.
Realistically, though, you should just use a JSONArrayRequest if you're going to be expecting a JSONArray.
i want to toast"Error" when jsonarray is empty
Simple enough.
arr = new JSONArray(response);
if (arr.length() == 0) {
// TODO: Toast
}
I would simply add two checks to your onResponse method:
...
public void onResponse(String response) {
// Check if the response itself is an empty string or null
if(TextUtils.isEmpty(response)) {
// Show your user feedback
return;
}
Datas.imageIds = new String[response.length()];
JSONArray arr = null;
try {
arr = new JSONArray(response);
// Check if your JSON has no elements in it
if(arr.length == 0) {
// Show your user feedback
return;
}
} catch (JSONException e1) {
e1.printStackTrace();
}
...
You have declared JSONArray arr = null;
After that you assign the server's JSON to that JSONArray.
Add a line after getting that
if(arr==null)
{
//toast
}
else
{
//whatever you want to do with JSON
}
StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.POST, AppConfig.URL_Gallery4,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(response.length()==0){
Toast.makeText(getActivity(),"no data found",Toast.LENGTH_SHORT).show();
}
else{
Datas.imageIds = new String[response.length()];
JSONArray arr = null;
try {
arr = new JSONArray(response);
} catch (JSONException e1) {
e1.printStackTrace();
}
if(arr.length()>0){
int i=0;
for (i = 0; i < arr.length(); i++) {
try {
JSONObject obj = arr.getJSONObject(i);
category = obj.getString("category_name");
selected = obj.getString("album_id");
imagename = obj.getString("org_image_name");
Datas.imageIds[i] = AppConfig.URL_IMAGE_temp+obj.getString("album_image").substring(3);
gridArray.add(new Item_album(Datas.imageIds[i]));
} catch (JSONException e) {
e.printStackTrace();
}
}
final int xl = i;
adapter = new CustomGrid_Album(kill.this,xl,gridArray);
adapter.notifyDataSetChanged();
grid1.setAdapter(adapter);
}else{
Toast.makeText(getActivity(),"no data found",Toast.LENGTH_SHORT).show();
}
}
pDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "No images in this gallery", Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
})
{
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("id", Uid);
return params;
}
};
Use the below code to check whether response is null or not and in object check whether it is having key or data with key is not null
if(response!=null){
try {
Datas.imageIds = new String[response.length()];
JSONArray arr = new JSONArray(response);
for (int i = 0; i < arr.length(); i++) {
try {
JSONObject obj = arr.getJSONObject(i);
if(obj!=null){
if(obj.has("category_name") && !obj.isNull("category_name"){
category = obj.getString("category_name");
}
if(obj.has("album_id") && !obj.isNull("album_id"){
selected = obj.getString("album_id");
}
if(obj.has("org_image_name") && !obj.isNull("org_image_name"){
imagename = obj.getString("org_image_name");
}
if(obj.has("album_image") && !obj.isNull("album_image"){
Datas.imageIds[i] = AppConfig.URL_IMAGE_temp+obj.getString("album_image").substring(3);
gridArray.add(new Item_album(Datas.imageIds[i]));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
final int xl = i;
adapter = new CustomGrid_Album(kill.this,xl,gridArray);
adapter.notifyDataSetChanged();
grid1.setAdapter(adapter);
pDialog.dismiss();
} catch (JSONException e1) {
e1.printStackTrace();
}
}
You are using StringRequest, instead of that use JsonArrayRequest to make request as below, so you will get response in onResponse methode when there is a valid JSONArray in response, and if there is no data then you will get response in onError method
JsonArrayRequest rReq = new JsonArrayRequest(Request.Method.GET,"url", new JSONObject(), new Response.Listener() {
#Override
public void onResponse(JSONArray response) {
Log.e(TAG, "onResponse: "+response.toString() );
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "onErrorResponse: "+error.getMessage() );
}
})
I have got a class called Client.class. Within this, I have got a method as follows where Im invoking a volley to fire api requests.
public void dispatchLoginRequest() {
// mRequestQueue = Volley.newRequestQueue(getApplicationContext());
// Log.d(TAG, "ADS " + frameLoginJson().toString());
pDialog.setMessage("Logging in ...");
showDialog();
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST, "http://52.11.242.90:8082/api/login", frameLoginJson(), new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
parseLoginResponse(response);
// aparjithaDb.parseLoginResponse(response, this);
Parser.getInstance().parseLoginResponse(response,this,getApplicationContext());
pDialog.hide();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "log" + frameLoginJson().toString());
error.printStackTrace();
pDialog.hide();
Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_SHORT).show();
}
});
AppController.getInstance().getRequestQueue().add(jsonArrayRequest);
}
I have the following method in other class called as Parse.class where im parsing the response and adding it to db.
public void parseLoginResponse(JSONArray response, ClientLogin clientLogin, ContextWrapper contextWrapper) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject value = response.getJSONObject(i);
JSONArray configuration = value.getJSONArray("configuration");
int group_id = value.getInt("group_id");
String group_name = value.getString("group_name");
JSONObject menu = value.getJSONObject("menu");
JSONObject menus = menu.getJSONObject("menus");
JSONArray master = menus.getJSONArray("Master");
JSONArray transaction = menus.getJSONArray("Transaction");
JSONArray report = menus.getJSONArray("Report");
boolean approvalExists = isApprovalExists(transaction, "Compliance Approval");
boolean taskExists = isTaskExists(transaction, "Compliance Task Details");
Toast.makeText(contextWrapper.getApplicationContext(), "COOL" + approvalExists, Toast.LENGTH_SHORT).show();
for (int j = 0; j < configuration.length(); j++) {
JSONObject jsonobject = configuration.getJSONObject(i);
int period_from = jsonobject.getInt("period_from");
int period_to = jsonobject.getInt("period_to");
int country_id = jsonobject.getInt("country_id");
int domain_id = jsonobject.getInt("domain_id");
Db.getInstance(contextWrapper).addClientConfig(new ClientConfig(j, String.valueOf(period_from), String.valueOf(country_id), String.valueOf(period_to), String.valueOf(domain_id), group_name, String.valueOf(group_id)));
}
Intent intent = new Intent(clientLogin, Client.class);
intent.putExtra("approvalExists", "" + approvalExists);
intent.putExtra("taskExists", "" + taskExists);
clientLogin.startActivity(intent);
// logClientDb();
} catch (Exception e) {
Toast.makeText(contextWrapper.getApplicationContext(), "Please Check your user credentials..." + e.toString(), Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}
The problem is that im getting the following error
Error:(91, 37) error: method parseLoginResponse in class Parser cannot be applied to given types;
required: JSONArray,ClientLogin,ContextWrapper
found: JSONArray,<anonymous Listener<JSONArray>>,Context
reason: actual argument <anonymous Listener<JSONArray>> cannot be converted to ClientLogin by method invocation conversion
Im just trying to externalise the way that Im parsing the json and adding it to db while using volley. How can I do so?
For request modify it as follow-
JsonArrayRequest request=new JsonArrayRequest(url,requestSuccessListener(),requestErrorListener());
now write u r public void external function requestSuccessListener and requestErrorListener. it will work.
I really need your help. I am building an Android app that needs a lot of HTTP requests such as logging to the server(check if user is exists or not) and storing the session to the database (user_sessions table), adding, updating and deleting records.
In my Login Activity, I have my AsyncTask (to check if user exits) and other background threads (logs the user session and download user info to database) . This is successful. Next, when I update the user info, it updates successfully. But what if I update using my web app? My should display the newly updated info on my android app. How can I resolve this problem?
This is what I've tried so far:
private void logSessionToServer() {
// TODO Auto-generated method stub
Thread thread = new Thread(){
public void run(){
strUsername = etUsername.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair( TAG_USERNAME, strUsername ));
// getting JSON Object
// Note it accepts POST method only
JSONObject json = jsonParser.makeHttpRequest(url_log_session,
"POST", params);
// check log cat from response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("", "Successfully logged session!");
} else {
// failed
Log.d("", "Not Successful!");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
thread.start();
}
/**
* Background Async Task to Create new record
* */
class LoginTask extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setIcon(R.drawable.upload);
pDialog.setTitle("Connecting to server");
pDialog.setMessage("Validating login details..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
*
* */
protected String doInBackground(String... args) {
strUsername = etUsername.getText().toString();
strPassword = etPassword.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair( TAG_USERNAME, strUsername ));
params.add(new BasicNameValuePair( TAG_PASSWORD, strPassword ));
// getting JSON Object
// Note it accepts POST method only
JSONObject json = jsonParser.makeHttpRequest(url_login,
"POST", params);
// check log cat from response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
logSessionToServer(); // Save login to server
saveUserInfoToDB(); // Save user info to DB
saveUserloggedIn(); // Save user logged in to preference
savePriestInfoToDB(); // Save priest to DB
Log.d("", "Successful Login!");
Intent i = new Intent(Login.this, MainActivity.class);
startActivity(i);
finish();
} else {
// failed
new Thread()
{
public void run()
{
runOnUiThread(new Runnable()
{
public void run()
{
Toast.makeText(getBaseContext(),
"Not Successful Login", Toast.LENGTH_SHORT).show();
}
});
}
}.start();
Log.d("", "Not Successful Login!");
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String result) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
private void saveUserInfoToDB() {
// TODO Auto-generated method stub
Thread thread = new Thread(){
public void run(){
// Create the array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given website URL in JSONfunctions.class
String result = JSONFunctions.getJSONfromURL(url_view_loggedUser_profile);
try {
JSONArray jr = new JSONArray(result);
for(int i=0;i<jr.length();i++)
{
HashMap<String, String> map = new HashMap<String, String>();
jb = (JSONObject)jr.get(i);
map.put(TAG_FIRSTNAME, jb.getString(TAG_FIRSTNAME));
map.put(TAG_MIDDLENAME, jb.getString(TAG_MIDDLENAME));
map.put(TAG_LASTNAME, jb.getString(TAG_LASTNAME));
map.put(TAG_EMAIL, jb.getString(TAG_EMAIL));
map.put(TAG_AGE, jb.getString(TAG_AGE));
map.put(TAG_GENDER, jb.getString(TAG_GENDER));
map.put(TAG_USERNAME, jb.getString(TAG_USERNAME));
map.put(TAG_PASSWORD, jb.getString(TAG_PASSWORD));
map.put(TAG_BARANGAY, jb.getString(TAG_BARANGAY));
map.put(TAG_COMPLETEADDRESS, jb.getString(TAG_COMPLETEADDRESS));
map.put(TAG_CUS_ID, jb.getString(TAG_CUS_ID));
map.put(TAG_REG_DATE, jb.getString(TAG_REG_DATE));
map.put(TAG_BD_MONTH, jb.getString(TAG_BD_MONTH));
map.put(TAG_BD_DATE, jb.getString(TAG_BD_DATE));
map.put(TAG_BD_YEAR, jb.getString(TAG_BD_YEAR));
arraylist.add(map);
String strCusID = jb.getString(TAG_CUS_ID);
String strFname = jb.getString(TAG_FIRSTNAME);
String strMname = jb.getString(TAG_MIDDLENAME);
String strLname = jb.getString(TAG_LASTNAME);
String strEmail = jb.getString(TAG_EMAIL);
String strAge = jb.getString(TAG_AGE);
String strGender = jb.getString(TAG_GENDER);
String strUsername = jb.getString(TAG_USERNAME);
String strPassword = jb.getString(TAG_PASSWORD);
String strBarangay = jb.getString(TAG_BARANGAY);
String strCompleteAddress = jb.getString(TAG_COMPLETEADDRESS);
String strRegDate = jb.getString(TAG_REG_DATE);
String strBDMonth = jb.getString(TAG_BD_MONTH);
String strBDDate = jb.getString(TAG_BD_DATE);
String strBDYear = jb.getString(TAG_BD_YEAR);
try{
dbHelper.insertEntry(strCusID, strFname, strMname, strLname, strEmail,
strAge, strGender, strUsername, strPassword,
strBarangay, strCompleteAddress, strRegDate,
strBDMonth, strBDDate, strBDYear);
Log.d("Response", "Successfully inserted record");
} catch (SQLiteException e) {
Log.d("Response", "Not successful");
}
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
}
};
thread.start();
}
private void savePriestInfoToDB() {
// TODO Auto-generated method stub
Thread thread = new Thread(){
public void run(){
// Create the array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given website URL in JSONfunctions.class
String result = JSONFunctions.getJSONfromURL(URL_VIEW_PRIESTS);
try {
JSONArray jr = new JSONArray(result);
for(int i=0;i<jr.length();i++)
{
HashMap<String, String> map = new HashMap<String, String>();
jb = (JSONObject)jr.get(i);
map.put(TAG_P_ID, jb.getString(TAG_P_ID));
map.put(TAG_P_FIRSTNAME, jb.getString(TAG_P_FIRSTNAME));
map.put(TAG_P_MIDDLENAME, jb.getString(TAG_P_MIDDLENAME));
map.put(TAG_P_LASTNAME, jb.getString(TAG_P_LASTNAME));
map.put(TAG_P_EMAIL, jb.getString(TAG_P_EMAIL));
map.put(TAG_P_AGE, jb.getString(TAG_P_AGE));
map.put(TAG_P_ADDRESS, jb.getString(TAG_P_ADDRESS));
map.put(TAG_P_CONTACT, jb.getString(TAG_P_CONTACT));
map.put(TAG_P_STATUS, jb.getString(TAG_P_STATUS));
arraylist.add(map);
String strP_ID = jb.getString(TAG_P_ID);
String strP_Fname = jb.getString(TAG_P_FIRSTNAME);
String strP_Mname = jb.getString(TAG_P_MIDDLENAME);
String strP_Lname = jb.getString(TAG_P_LASTNAME);
String strP_Email = jb.getString(TAG_P_EMAIL);
String strP_Age = jb.getString(TAG_P_AGE);
String strP_Address = jb.getString(TAG_P_ADDRESS);
String strP_Status = jb.getString(TAG_P_STATUS);
String strP_Contact = jb.getString(TAG_P_CONTACT);
try{
dbHelper.insertPriest(strP_ID, strP_Fname, strP_Mname,
strP_Lname, strP_Email, strP_Age,
strP_Address, strP_Status, strP_Contact);
Log.d("Response - Priest", "Successfully inserted record");
} catch (SQLiteException e) {
Log.d("Response - Priest", "Not successful");
}
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
}
};
thread.start();
}
Feel free to check out my codes and give feedback if this is the best practice for HTTP requests. I am new to Web Services so I really need your help. Any help will be greatly appreciated. Thanks
Well what I just said: you write a thread which downloads user-info every 5 seconds. then it compares the user info downloaded with the user info that is already stored on your device. if there is a difference, an update has been made, and your thread invokes a new download of the updated user info.