JSONObject isn't encoding like it should be? - java

This is server side code
<?php
require('connection.php');
require('functions.php');
$inputJSON = file_get_contents('php://input');
$aReuestData = json_decode( $inputJSON, TRUE ); //convert JSON into array
$user_email = $aReuestData['user_email'];
$user_password = $aReuestData['user_password'];
$user_uniq = $aReuestData['user_uniq_id'];
if((($user_password !='') && ($user_email !=''))|| ($user_uniq!=''))
{
$uname = $user_email;
$pword = $user_password;
$format ='json';
if(($user_password !='') && ($user_email !='')){
echo $checkUser = checkLogin($uname,$pword);
}
else{
$checkUser = checkLoginFacebook($user_uniq);
}
//print_r($checkUser);
if($checkUser['id'] > 0)
{
$result = $checkUser;
}else{
$result = "false";
}
}else{
$result = "Enter username and password";
}
$records = array("result"=> $result);
echo $_REQUEST['jsoncallback']. json_encode($records);
?>
and my code for login activity is
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.TextView;
import android.widget.Toast;
import com.android.volley.Cache;
import com.android.volley.Network;
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.BasicNetwork;
import com.android.volley.toolbox.DiskBasedCache;
import com.android.volley.toolbox.HurlStack;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
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;
public class Login extends MainActivity {
//private Button button;
//private TextView welcome;
//private EditText username;
//private EditText password;
//private JSONObject jsonObject;
private RequestQueue requestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Cache cache = new DiskBasedCache(getCacheDir(),1024 * 1024);
Network network = new BasicNetwork(new HurlStack());
requestQueue= new RequestQueue(cache,network);
final TextView send = (TextView)findViewById(R.id.send);
final TextView hello = (TextView)findViewById(R.id.mess);
EditText username = (EditText)findViewById(R.id.edituser);
EditText password = (EditText)findViewById(R.id.editpass);
Button button = (Button)findViewById(R.id.signin);
final JSONObject jsonObject = new JSONObject();
try {
// jsonObject.put("Content-Type: ","application-json");
jsonObject.put("user_email",username.getText().toString().trim());
jsonObject.put("user_password",password.getText().toString().trim());
} catch (JSONException e) {
e.printStackTrace();
}
final HashMap<String,String> params = new HashMap<String, String>();
params.put("user_email",username.getText().toString().trim());
params.put("user_password",password.getText().toString().trim());
String json = "{\"user_email\":\"ankur#gmail.com\",\"user_password\":\"123456\"} ";
JSONObject json1 = new JSONObject();
try {
json1 = new JSONObject(json);
} catch (JSONException e) {
e.printStackTrace();
}
requestQueue.start();
final String url = "http://demo4u.org/leaveapp/ws/login.php";
send.setText(json1.toString());
final JSONObject finalJson = json1;
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(ApiMethods.login, finalJson,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(Login.this,"Passed",Toast.LENGTH_LONG).show();
hello.setText(response.toString());
Toast.makeText(Login.this,jsonObject.toString(),Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Login.this,"Error",Toast.LENGTH_LONG).show();
}
}
){
#Override
public Map<String,String> getHeaders(){
HashMap<String,String> headers = new HashMap<>();
headers.put("Accept", "application/json");
headers.put("Content-Type","application/json");
return headers;
}
};
requestQueue.add(jsonObjectRequest);
}
});
}
}
and the only thing that I get returned is
$result = "Enter username and password";
what am I doing wrong?
am I to include JSON header or something ???
Please reply in detailed view cause I'm new to android.....
The input is
{"user_email":"ankur#gmail.com","user_password":"123456"}
and server response would be
Array{"result":{"id":"1","name":"ankur","email":"ankur#gmail.com","address":"b-block","designation":"devloper","department":"development","balanceleave":"5"}}
login php server is : http://demo4u.org/leaveapp/ws/login.php

Try setting the headers by overriding the getHeaders() method in JsonObjectRequest
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(...your arguments here) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headerParameters = new HashMap<>();
headerParameters.put("Accept", "application/json");
headerParameters.put("Content-Type", "application/json");
return headerParameters;
}
};

Related

Value Connected of type java.lang.String cannot be converted error to JSONObject error

so I'm new to android apps developement and currently trying to make an app which lets the user login with their info from the database.
I have followed tutorials from youtube and currently am stuck with this problem: Value Connected of type java.lang.String cannot be converted to JSONObject
Login.php
<?php if ($_SERVER['REQUEST_METHOD']=='POST') {
$email = $_POST['email'] ?? '';
$password = $_POST['password'] ?? '';
require_once 'connect.php';
$sql = "SELECT * FROM users_table WHERE email='$email' ";
$response = mysqli_query($conn, $sql);
$result = array();
$result['login'] = array();
if ( mysqli_num_rows($response) === 1 ) {
$row = mysqli_fetch_assoc($response);
if ( password_verify($password, $row['password']) ) {
$index['name'] = $row['name'];
$index['email'] = $row['email'];
$index['id'] = $row['id'];
array_push($result['login'], $index);
$result['success'] = "1";
$result['message'] = "success";
echo json_encode($result);
mysqli_close($conn);
} else {
$result['success'] = "0";
$result['message'] = "error";
echo json_encode($result);
mysqli_close($conn);
}?>
Login class
import androidx.appcompat.app.AppCompatActivity;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkError;
import com.android.volley.NoConnectionError;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
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;
public class Login extends AppCompatActivity {
private EditText email, password;
private Button btn_login;
private ProgressBar loading;
private static String URL_LOGIN = "https://interntest1.000webhostapp.com/login.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
loading = findViewById(R.id.loading);
email = findViewById(R.id.email);
password = findViewById(R.id.password);
btn_login = findViewById(R.id.btn_login);
btn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mEmail = email.getText().toString().trim();
String mPass = password.getText().toString().trim();
if (!mEmail.isEmpty() || !mPass.isEmpty()) {
Login(mEmail, mPass);
} else {
email.setError("Please insert email");
password.setError("Please insert password");
}
}
});
}
private void Login(final String email, final String password) {
loading.setVisibility(View.VISIBLE);
btn_login.setVisibility(View.GONE);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_LOGIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
JSONArray jsonArray = jsonObject.getJSONArray("login");
if (success.equals("1")) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
String name = object.getString("name").trim();
String email = object.getString("email").trim();
String id = object.getString("id").trim();
loading.setVisibility(View.GONE);
}
}
} catch (JSONException e) {
e.printStackTrace();
loading.setVisibility(View.GONE);
btn_login.setVisibility(View.VISIBLE);
Toast.makeText(Login.this, "Error " +e.toString(), Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
loading.setVisibility(View.GONE);
btn_login.setVisibility(View.VISIBLE);
Toast.makeText(Login.this, "Error " +error.toString(), Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("email",email);
params.put("password",password);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}

JSON Issue - how to fix that?

This is my code for getting the data from JSON, it will contain only one row,
but it will give output for only "pro_name" for left of the values it will give just dots(......).
package com.example.sh_enterprises;
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
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.ArrayList;
import java.util.List;
public class Detailes extends AppCompatActivity {
//this is the JSON Data URL
//make sure you are using the correct ip else it will not work
public static String URL_PRODUCTS, pass1,pass2 ;
public static String ptopic,psubcode;
private static ProgressDialog progressDialog;
//a list to store all the products
List<pro_data> productList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detailes);
Intent i = getIntent();
pass1 = i.getStringExtra("pro_id");
//Toast.makeText(this,"HI THIS IS "+pass,Toast.LENGTH_SHORT).show();
//URL_PRODUCTS = "https://premnathindia.000webhostapp.com/Api.php?p1="+pass;
URL_PRODUCTS = "http://192.168.225.25/prem/Api.php?p1="+pass1+"&p2=det";
Toast.makeText(this, URL_PRODUCTS, Toast.LENGTH_SHORT).show();
productList = new ArrayList<>();
//this method will fetch and parse json
//to display it in recyclerview
loadProducts();
}
private void loadProducts() {
prefConfig product = new prefConfig(this);
String str = product.read_ret_id();
Toast.makeText(this,str,Toast.LENGTH_SHORT).show();
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Please wait...");
progressDialog.show();
/*
* Creating a String Request
* The request type is GET defined by first parameter
* The URL is defined in the second parameter
* Then we have a Response Listener and a Error Listener
* In response listener we will get the JSON response as a String
* */
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_PRODUCTS,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//converting the string to json array object
JSONArray array = new JSONArray(response);
//traversing through all the object
for (int i = 0; i < 1; i++) {
//getting product object from json array
JSONObject product = array.getJSONObject(i);
product.getString("pro_id");
String st;
TextView a = findViewById(R.id.pro_name);
TextView b = findViewById(R.id.weight);
TextView c = findViewById(R.id.base_amount);
TextView d = findViewById(R.id.mass_amonut);
TextView e = findViewById(R.id.brand);
TextView f = findViewById(R.id.catogery);
String st1 = product.getString("pro_name");
a.setText(st1);
st = product.getString("weight");
b.setText(st);
st = product.getString("total_amount");
d.setText(st);
//st = product.getString("pro_img_url");
st = product.getString("base_amount");
c.setText(st);
//st = product.getString("disc");
st = product.getString("brands");
e.setText(st);
st = product.getString("categories");
f.setText(st);
}
progressDialog.dismiss();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//adding our stringrequest to queue
Volley.newRequestQueue(this).add(stringRequest);
}
public void downme_ooi(View view) {
String pro_id = ((TextView) view).getText().toString();
Intent i = new Intent(this,Detailes.class);
i.putExtra("pro_id",pro_id);
startActivity(i);
}
public void go_back(View view) {
super.onBackPressed();
}
}
Sorry I made the Mistake that in TextView I put the text as password .

Android: How to retrieve a single data from a web server and display it to a textview?

i want to display an employee last clock-in from a web server. The problem is i'm not really sure how to retrieve a single last clock-in and display it to a textview. Here is my code, JSONParser.java:
package com.example.win7.simpleloginapp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.SocketException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
int timeout=10000; //in milisecond = 10 detik
// constructor
public JSONParser() {
//timeout = new Values().gettimeout();
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, timeout);
HttpConnectionParams.setSoTimeout(httpParameters, timeout);
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (SocketException ste)
{
Log.e("Timeout Exception: ", ste.toString());
}
catch (ConnectTimeoutException e)
{
Log.e("Timeout Exception: ", e.toString());
}
catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
ServerRequest.java:
package com.example.win7.simpleloginapp;
import android.app.Activity;
import android.app.Application;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.io.HttpRequestParser;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
public class ServerRequest {
ProgressDialog progressDialog;
public static final int CONNECTION_TIMEOUT = 1000 * 15;
public static final String SERVER_ADDRESS = ".................net";
final static String TAG_USER = "user";
private Context mContext;
SharedPreferences sharedPreferences;
public static final String mypreference = "mypref";
public static final String NameStr = "Name";
JSONArray user;
JSONParser jsonParser = new JSONParser();
public ServerRequest(Context context) {
progressDialog = new ProgressDialog(context);
progressDialog.setCancelable(false);
progressDialog.setTitle("Processing..");
progressDialog.setMessage("Please Wait....");
mContext = context;
}
public void storeUserDataInBackground(user user, GetUserCallback userCallback) {
progressDialog.show();
new StoreUserDataAsyncTask(user, userCallback).execute();
}
public void fetchUserDataInBackground(user user, GetUserCallback callBack) {
progressDialog.show();
new fetchUserDataAsyncTask(user, callBack).execute();
}
public class StoreUserDataAsyncTask extends AsyncTask<Void, Void, Void> {
user user;
GetUserCallback userCallback;
public StoreUserDataAsyncTask(user user, GetUserCallback userCallback) {
this.user = user;
this.userCallback = userCallback;
}
#Override
protected Void doInBackground(Void... params) {
ArrayList<NameValuePair> dataToSend = new ArrayList<>();
dataToSend.add(new BasicNameValuePair("username", user.username));
dataToSend.add(new BasicNameValuePair("password", user.password));
HttpParams httpRequestParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT);
HttpClient client = new DefaultHttpClient(httpRequestParams);
HttpPost post = new HttpPost("http://.........................../register.php");
try {
post.setEntity(new UrlEncodedFormEntity(dataToSend));
client.execute(post);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
progressDialog.dismiss();
userCallback.done(null);
super.onPostExecute(aVoid);
}
}
public class fetchUserDataAsyncTask extends AsyncTask< Void, Void, user> {
user user;
GetUserCallback userCallback;
public fetchUserDataAsyncTask(user user, GetUserCallback userCallback) {
this.user = user;
this.userCallback = userCallback;
}
#Override
protected user doInBackground(Void... params) {
ArrayList<NameValuePair> dataToSend = new ArrayList<>();
dataToSend.add(new BasicNameValuePair("username", user.username));
dataToSend.add(new BasicNameValuePair("password", user.password));
HttpParams httpRequestParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT);
HttpClient client = new DefaultHttpClient(httpRequestParams);
HttpPost post = new HttpPost("................................../fetchUserData.php");
user returnedUser = null;
try {
post.setEntity(new UrlEncodedFormEntity(dataToSend));
HttpResponse httpResponse = client.execute(post);
HttpEntity entity = httpResponse.getEntity();
String result = EntityUtils.toString(entity);
JSONObject jObject = new JSONObject(result);
if(jObject.length()==0)
{
returnedUser = null;
}
else
{
String Name1 = jObject.getString("Name");
//String Name1 = "ekin";
storeData(Name1);
//Name1 = "hello";
returnedUser = new user(user.username, user.password);
}
} catch (Exception e) {
e.printStackTrace();
}
return returnedUser;
}
#Override
protected void onPostExecute(user returnedUser) {
progressDialog.dismiss();
userCallback.done(returnedUser);
super.onPostExecute(returnedUser);
}
}
public SharedPreferences getSharedPref(){
return mContext.getSharedPreferences(mContext.getPackageName(), Context.MODE_PRIVATE);
}
public void storeData(String Name1) {
getSharedPref().edit().putString("data", Name1).apply();
}
public String getData(){
return getSharedPref().getString("data", "");
}
}
And here is the MainActivity.java:
package com.example.win7.simpleloginapp;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.InputFilter;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AnalogClock;
import android.widget.Button;
import android.widget.DigitalClock;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.json.JSONException;
import android.app.AlertDialog;
import android.location.LocationListener;
import com.example.win7.simpleloginapp.model.JSONParser2;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
Button button_logout;
TextView etUsername , etName, lastTimeDisp, lastDateDisp; //baru
UserLocalStore userLocalStore;
Button clockIN1, clockOUT1;
Date date = new Date();
String AndroidId;
String username;
double longitude;
double latitude;
private TextView locationText;
private TextView addressText;
private GoogleMap map;
private LocationManager locationMangaer = null;
private LocationListener locationListener = null;
private Button btnGetLocation = null;
private EditText editLocation = null;
private ProgressBar pb = null;
private static final String TAG = "Debug";
private Boolean flag = false;
JSONArray user = null;
JSONParser jsonParser = new JSONParser();
public static final String TAG_SUCCESS = "success";
public static final String TAG_USER = "user";
public static final String TAG_STAFF_ID = "staffID";
public static final String TAG_DATE = "date";
public static final String TAG_TIME = "time";
public static final String TAG_LONG = "longitude";
public static final String TAG_LAT = "latitude";
private Button scannerButton;
private Button camButton;
String staffIDStr, dateStr, timeStr, latitudeStr, longitudeStr;
String user_name;
SharedPreferences sharedPreferences;
public static final String mypreference = "MyPrefs" ;
public static final String NameStr = "Name";
ActionBar actionbar;
TextView textview;
LayoutParams layoutparams;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBarTitleGravity();
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
Toast.makeText(this, "GPS is Enabled in your device", Toast.LENGTH_SHORT).show();
}else{
showGPSDisabledAlertToUser();
}
ActionBar actionBar = getSupportActionBar();
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#3B5999")));
actionBar.setDisplayUseLogoEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
setContentView(R.layout.activity_main);
etUsername = (TextView) findViewById(R.id.etUsername);
etName = (TextView) findViewById(R.id.etName);
lastTimeDisp = (TextView) findViewById(R.id.lastTimeDisp); //baru
lastDateDisp = (TextView) findViewById(R.id.lastDateDisp); //baru
button_logout = (Button) findViewById(R.id.bLogout);
AnalogClock ac = (AnalogClock) findViewById(R.id.analogClock1);
DigitalClock dc = (DigitalClock) findViewById(R.id.digitalClock1);
clockIN1 = (Button) findViewById(R.id.clockIN);
clockOUT1 = (Button) findViewById(R.id.clockOUT);
etUsername.setFilters(new InputFilter[]{new InputFilter.AllCaps()});
etName.setFilters(new InputFilter[]{new InputFilter.AllCaps()});
super.onPause();
SharedPreferences prefs = getSharedPreferences("X", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("lastActivity", getClass().getName());
editor.apply(); //baru - tukar commit() ke apply()
ServerRequest serverRequest = new ServerRequest(getApplicationContext());
ServerRequest2 serverRequest2 = new ServerRequest2(getApplicationContext());
Log.d("", "The value is : " + serverRequest.getData());
String username1 = serverRequest.getData();
String timeL = serverRequest2.getData();
String dateL = serverRequest2.getData();
etName.setText(username1);
lastTimeDisp.setText(timeL); //baru
lastDateDisp.setText(dateL); //baru
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
locationText = (TextView) findViewById(R.id.location);
addressText = (TextView) findViewById(R.id.address);
replaceMapFragment();
clockIN1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//date.setTime(System.currentTimeMillis()); //set to current time
clockIN1.setClickable(false);
Calendar c = Calendar.getInstance();
dateStr = c.get(Calendar.YEAR) + "-" + c.get(Calendar.MONTH) + "-" + c.get(Calendar.DAY_OF_MONTH);
timeStr = c.get(Calendar.HOUR_OF_DAY) + ":" + c.get(Calendar.MINUTE);
staffIDStr = etUsername.getText().toString();
new createClockIn().execute();
clockIN1.setEnabled(false);
clockIN1.setClickable(false);
}
});
userLocalStore = new UserLocalStore(this);
}
private void ActionBarTitleGravity() {
actionbar = getSupportActionBar();
textview = new TextView(getApplicationContext());
layoutparams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
textview.setLayoutParams(layoutparams);
textview.setText("MysysESS");
textview.setTextColor(Color.WHITE);
textview.setGravity(Gravity.CENTER);
textview.setTextSize(25);
textview.setTypeface(Typeface.DEFAULT_BOLD);
actionbar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
actionbar.setCustomView(textview);
}
class createClockIn extends AsyncTask<String, String, String> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("LOADING.");
dialog.setIndeterminate(false);
dialog.setCancelable(false);
dialog.show();
}
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(TAG_STAFF_ID, staffIDStr));
params.add(new BasicNameValuePair(TAG_DATE, dateStr));
params.add(new BasicNameValuePair(TAG_TIME, timeStr));
params.add(new BasicNameValuePair(TAG_LONG, longitudeStr));
params.add(new BasicNameValuePair(TAG_LAT, latitudeStr));
JSONObject json = jsonParser.makeHttpRequest("http://.........................../createClockIN.php", "POST", params);
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
finish();
} else {
return "gagal_database";
}
} catch (JSONException e)
{
e.printStackTrace();
return "gagal_koneksi_or_exception";
}
return "sukses";
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result.equalsIgnoreCase("gagal_database")) {
dialog.dismiss();
Toast.makeText(MainActivity.this, "There is a problem , check your connection DB!", Toast.LENGTH_SHORT).show();
} else if (result.equalsIgnoreCase("gagal_koneksi_or_exception")) {
dialog.dismiss();
Toast.makeText(MainActivity.this, "There is a problem , check your connection!", Toast.LENGTH_SHORT).show();
} else if (result.equalsIgnoreCase("sukses")) {
dialog.dismiss();
Toast.makeText(MainActivity.this, "Lets work!", Toast.LENGTH_SHORT).show();
String staffID1 = etUsername.getText().toString();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("username", staffID1);
startActivity(intent);
}
}
}
//on start function login function
#Override
protected void onStart() {
super.onStart();
if (authenticate() == true)
displayUserDetails();
else
startActivity(new Intent(MainActivity.this, login.class));
}
private boolean authenticate() {
return userLocalStore.getUserLoggedIn();
}
private void displayUserDetails() {
user user = userLocalStore.getLoggedInUser();
etUsername.setText(user.username);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
LinearLayout main_view = (LinearLayout) findViewById(R.id.main_view);
switch (item.getItemId()) {
case R.id.logout:
userLocalStore.clearUserData();
startActivity(new Intent(this, login.class));
finish();
return true;
case R.id.history:
if (item.isChecked())
item.setChecked(false);
else
item.setChecked(true);
String username1 = etUsername.getText().toString();
Intent intent = new Intent(getApplicationContext(), ListHistory.class);
intent.putExtra("username", username1);
startActivity(intent);
return true;
case R.id.location:
if (item.isChecked())
item.setChecked(false);
else
item.setChecked(true);
String username2 = etUsername.getText().toString();
Intent intent2 = new Intent(getApplicationContext(), LocationActivity.class);
intent2.putExtra("username", username2);
startActivity(intent2);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onBackPressed() {
// super.onBackPressed(); // Comment this super call to avoid calling finish()
}
public void callBackDataFromAsyncTask(String address) {
addressText.setText(address);
}
private void replaceMapFragment() {
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
View frag = findViewById(R.id.map);
frag.setVisibility(View.INVISIBLE);
map.getUiSettings().setZoomGesturesEnabled(true);
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
map.setMyLocationEnabled(true);
map.setOnMyLocationChangeListener(myLocationChangeListener());
}
private GoogleMap.OnMyLocationChangeListener myLocationChangeListener() {
return new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
double longitude = location.getLongitude();
double latitude = location.getLatitude();
Marker marker;
marker = map.addMarker(new MarkerOptions().position(loc));
map.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));
locationText.setText("You are at [" + longitude + " ; " + latitude + " ]");
longitudeStr = Double.toString(longitude);
latitudeStr = Double.toString(latitude);
if ((longitude > 101.650000 && longitude < 101.670000 && latitude > 2.925000 && latitude < 2.927000) ||
(longitude > 101.640000 && longitude < 101.660000 && latitude > 2.900000 && latitude < 2.920000) ||
(longitude > 101.680000 && longitude < 101.700000 && latitude > 3.140000 && latitude < 3.170000) ||
(longitude > 103.620000 && longitude < 103.640000 && latitude > 1.640000 && latitude < 1.660000))
{
clockIN1.setEnabled(true);
scannerButton.setEnabled(true);
camButton.setEnabled(true);
} else {
Toast.makeText(MainActivity.this, "YOU ARE NOT IN THE OFFICE!", Toast.LENGTH_SHORT).show();
clockIN1.setEnabled(false);
scannerButton.setEnabled(false);
camButton.setEnabled(false);
}
new GetAddressTask(MainActivity.this).execute(String.valueOf(latitude), String.valueOf(longitude));
}
};
}
private void showGPSDisabledAlertToUser()
{
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("GPS is disabled in your device. Would you like to enable it?")
.setCancelable(false)
.setPositiveButton("Settings your GPS",
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
Intent callGPSSettingIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(callGPSSettingIntent);
}
});
alertDialogBuilder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
}
For your information, I have to retrieve the data from another web server url(http://........................./lastClock.php) and the name of the entity from the table is dclkrec(represent date) and cclktime(represent time).
Any help from you guys would be very appreciated. Thank you in advanced.
You are doing a lot of wheel reinvention here. There are tools for networking and serialising/deserialising data.
For networking I can recommend Retrofit
Working with JSON objects Gson
Try these and your life will be much easier. Trust me. It is worth investing a little time.

Unable to get JSONObject from a url

I am developing an android app which requires a "token" to login. This token is available along with some other details at https://demo.vtiger.com/webservice.php?operation=getchallenge&username=admin. I tried to fetch the data by JSON parsing but it is not working properly. Please help me. Thanks. This how I coded:-
//MainActivity.java
package com.example.login1;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity_old extends Activity {
//URL to get JSON Array
private static String url = "http://demo.vtiger.com/webservice.php?operation=getchallenge&username=admin";
//JSON Node Names
private static final String TAG_RESULT = "result";
private static final String TAG_TOKEN = "token";
String token = null;
EditText userid, accesskey;
Button login;
TextView gettoken;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
this.gettoken = (TextView)findViewById(R.id.lblToken);
new AsyncTask<Void, Void, Void>() {
JSONArray result;
#Override
protected Void doInBackground(Void... params) {
// Creating new JSON Parser
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting JSON Array
result = json.getJSONArray(TAG_RESULT);
JSONObject json_result = json.getJSONObject(TAG_RESULT);
// Storing JSON item in a Variable
token = json_result.getString(TAG_TOKEN);
//Importing TextView
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
//Set JSON Data in TextView
gettoken.setText(token);
}
}.execute();
userid = (EditText) findViewById(R.id.txtUserid);
accesskey = (EditText) findViewById(R.id.txtPassword);
Button login = (Button) findViewById(R.id.btnLogin);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
/* This code get the values from edittexts */
String useridvalue = userid.getText().toString();
String accesskeyvalue = accesskey.getText().toString();
/*To check values what user enters in Edittexts..just show in logcat */
Log.d("useridvalue",useridvalue);
Log.d("accesskeyvalue",accesskeyvalue);
String md=md5(accesskeyvalue + token);
System.out.println(md);
}
public String md5(String s)
{
MessageDigest digest;
try
{
digest = MessageDigest.getInstance("MD5");
digest.update(s.getBytes(),0,s.length());
String hash = new BigInteger(1, digest.digest()).toString(16);
return hash;
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
return "";
}
});
}
}
"result" is JSONObject instead of JSONArray. get token String from result JSONObject as:
JSONObject json_result = json.getJSONObject(TAG_RESULT);
// Storing JSON item in a Variable
token = json_result.getString(TAG_TOKEN);
Just make these two changes.
result = json.getJSONArray(TAG_RESULT);
to
result = json.getJSONObject(TAG_RESULT);
and
JSONArray result;
to
JSONObject result;

How do I pass parameter to webservice and get json datas in listview

Hi (fresher to andorid)
I'm developing an android application which will use the webservice which should accept 1 parameter from the user and based on that the value is fetched datas from DB(sql server 2008) and bind that to android:LISTVIEW.
Without using the parameter my android application is working fine.But when i altered my webserservice to accept parameter and call it in android it is not displaying the result based on the given value instead of that it displays all values.
Here is my webservice code;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.ComponentModel;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class JService : System.Web.Services.WebService
{
public JService () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public void Cargonet(string jobno)
{
try
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["NSConstr"].ToString());
SqlCommand cmd = new SqlCommand();
//cmd.CommandText = "SELECT id,name,salary,country,city FROM EMaster where age = '" + jobno + "'";
cmd.CommandText = "SELECT [Id] as Id,[Status] as status ,[DateTime] as DateTime FROM [Attendance].[dbo].[cargo] WHERE JobNo= '" + jobno + "' ";
DataSet ds = new DataSet();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.SelectCommand.Connection = con;
da.Fill(dt);
con.Close();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row = null;
foreach (DataRow rs in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, rs[col].ToString().Trim());
}
rows.Add(row);
}
this.Context.Response.ContentType = "application/json; charset=utf-8";
this.Context.Response.Write(serializer.Serialize(new { Cargo = rows }));
}
catch (Exception ex)
{
//return errmsg(ex);
}
}
}
Here is my android code(Main.java):
package com.example.cargotracking;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
ListView list;
TextView Id;
TextView Status;
TextView DateTime;
Button Btngetdata;
String JobNo;
EditText editText1;
ArrayList<HashMap<String, String>> CargoTracklist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url = "http://ip/testing/TrackId.asmx/Cargonet";
//JSON Node Names
private static final String TAG_CargoTrack = "Cargo";
private static final String TAG_Id = "Id";
private static final String TAG_Status = "Status";
private static final String TAG_DateTime = "DateTime";
JSONArray Cargo = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CargoTracklist = new ArrayList<HashMap<String, String>>();
Btngetdata = (Button)findViewById(R.id.button1);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
Status = (TextView)findViewById(R.id.textView2);
Id= (TextView)findViewById(R.id.textView1);
DateTime = (TextView)findViewById(R.id.textView3);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
// List params = new ArrayList();
params.add(new BasicNameValuePair("JobNo","01"));
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url,params);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
Cargo = json.getJSONArray(TAG_CargoTrack);
for(int i = 0; i < Cargo.length(); i++){
JSONObject c = Cargo.getJSONObject(i);
// Storing JSON item in a Variable
String Status = c.getString(TAG_Status);
String Id = c.getString(TAG_Id);
String DateTime = c.getString(TAG_DateTime);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_Status, Status);
map.put(TAG_Id, Id);
map.put(TAG_DateTime, DateTime);
CargoTracklist.add(map);
list=(ListView)findViewById(R.id.listView1);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, CargoTracklist,
R.layout.listview,
new String[] { TAG_Status,TAG_Id, TAG_DateTime }, new int[] {
R.id.textView2,R.id.textView1, R.id.textView3});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at "+CargoTracklist.get(+position).get("Id"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Here is my json parser code:
package com.example.cargotracking;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
//public JSONObject getJSONFromUrl(String url, List params) {
public JSONObject getJSONFromUrl(String url, List<BasicNameValuePair> params) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
please help me to resolve this.
Thanks in advance

Categories

Resources