Android Php Mysql Date Range Search - java

Can anyone help me? I'm developing an android app in android studio which will implement a Date Range search. the user will select the between date the "FROM" date and the "TO" date then the result will filter in a recyclerview. I'm using php mysql as our query. Hoping for a good and better reply. Thanks in advance
private class FilterDate extends AsyncTask {
ProgressDialog pdLoading = new ProgressDialog(Complaint.this);
HttpURLConnection conn;
URL url = null;
String from;
String to;
public FilterDate(String from,String to) {
this.from = from;
this.to = to;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(String... params) {
try {
// Enter URL address where your php file resides
url = new URL("http://192.168.0.100/Android/filter.php");
} catch (MalformedURLException e) {
e.printStackTrace();
// TODO Auto-generated catch block
return e.toString();
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
// setDoInput and setDoOutput to true as we send and recieve data
conn.setDoInput(true);
conn.setDoOutput(true);
conn.connect();
// add parameter to our above url
Uri.Builder builder1 = new Uri.Builder().appendQueryParameter("from", from);
String query1 = builder1.build().getEncodedQuery();
OutputStream os1 = conn.getOutputStream();
BufferedWriter writer1 = new BufferedWriter(new OutputStreamWriter(os1, "UTF-8"));
writer1.write(query1);
writer1.flush();
writer1.close();
os1.close();
conn.connect();
Uri.Builder builder2 = new Uri.Builder().appendQueryParameter("to", from);
String query2 = builder2.build().getEncodedQuery();
OutputStream os2 = conn.getOutputStream();
BufferedWriter writer2 = new BufferedWriter(new OutputStreamWriter(os1, "UTF-8"));
writer2.write(query2);
writer2.flush();
writer2.close();
os2.close();
conn.connect();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("Connection error");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
//this method will be running on UI thread suggestion
ArrayList<String> dataList = new ArrayList<String>();
pdLoading.dismiss();
// pdLoading.dismiss();
List<DataComplaints> data = new ArrayList<>();
pdLoading.dismiss();
if (result.equals("no rows")) {
Toast.makeText(Complaint.this, "No Results found for entered query", Toast.LENGTH_SHORT).show();
} else {
try {
JSONArray jArray = new JSONArray(result);
// Extract data from json and store into ArrayList as class objects
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
DataComplaints healthData = new DataComplaints();
healthData.idNum = json_data.getString("student_number");
healthData.lastName = json_data.getString("lastname");
healthData.firstName = json_data.getString("firstname");
healthData.middleName = json_data.getString("middlename");
healthData.complaint = json_data.getString("common_type");
healthData.medicine = json_data.getString("medicinetype");
healthData.date = json_data.getString("date");
healthData.time = json_data.getString("time");
data.add(healthData);
dataList.add(json_data.getString("date"));
}
strArrData = dataList.toArray(new String[dataList.size()]);
// Setup and Handover data to recyclerview
mRVFish = (RecyclerView) findViewById(R.id.studentList);
mAdapter = new AdapterComplaints(Complaint.this, data);
mRVFish.setAdapter(mAdapter);
mRVFish.setLayoutManager(new LinearLayoutManager(Complaint.this));
} catch (JSONException e) {
// You to understand what actually error is and handle it appropriately
Toast.makeText(Complaint.this, "Error in Fetching Data", Toast.LENGTH_LONG).show();
Toast.makeText(Complaint.this, "Error!", Toast.LENGTH_LONG).show();
}
}
}
}
This is my query in php:
<?php
$host='127.0.0.1';
$username='root';
$pwd='';
$db="cjc_clinic";
$con=mysqli_connect($host,$username,$pwd,$db) or die('Unable to connect');
if(mysqli_connect_error($con))
{
echo "Failed to Connect to Database ".mysqli_connect_error();
}
$From=$_POST['from'];
$To=$_POST['to'];
//$sql="SELECT * from studentcomplaint_view where lastname LIKE '%$name%'";
//$sql="SELECT * FROM studentcomplaint_view where CONCAT(lastname,' ',firstname) LIKE '%$name%'";
//$sql="SELECT * FROM studentcomplaint_view WHERE Date >= '$From' AND Date <='$To'";
$sql="SELECT * FROM studentcomplaint_view WHERE Date BETWEEN '$From' AND '$To'";
$query=mysqli_query($con,$sql);
if($query){
while($row=mysqli_fetch_array($query))
{
$data[]=$row;
}
print(json_encode($data));
}else
{
echo('Not Found ');
}
mysqli_close($con);
?>

Related

Send data(Client_id=1,Staff_id=2) from android application to tomcat server

i want to send data from android application to tomcat java server.
Data is just one is client_id which is 1 and second is staff_id which is 2.
after authenticate the client id and staff id from tomcat show me a toast of success....please help...
Code is here
public class MyAsyncTasks extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// display a progress dialog for good user experiance
}
#Override
protected String doInBackground(String... params) {
// implement API in background and store the response in current variable
String current = "";
try {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL("http://192.168.1.13:8080/digitaldisplay/s/m/data");
urlConnection = (HttpURLConnection) url
.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isw = new InputStreamReader(in);
int data = isw.read();
while (data != -1) {
current += (char) data;
data = isw.read();
System.out.print(current);
}
// return the data to onPostExecute method
return current;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
} catch (Exception e) {
e.printStackTrace();
return "Exception: " + e.getMessage();
}
return current;
}
#Override
protected void onPostExecute(String s) {
Toast.makeText(Register.this, "success", Toast.LENGTH_SHORT).show();
Log.d("data", s.toString());
// dismiss the progress dialog after receiving data from API
try {
// JSON Parsing of data
JSONArray jsonArray = new JSONArray(s);
JSONObject oneObject = jsonArray.getJSONObject(0);
// Pulling items from the array
client = Integer.parseInt(oneObject.getString("client"));
staff = Integer.parseInt(oneObject.getString("staff"));
} catch (JSONException e) {
e.printStackTrace();
}
} }}
The logic in your code looks off to me. This is the pattern I usually follow when making a REST call from an activity using HttpURLConnection:
try {
String endpoint = "http://192.168.1.13:8080/digitaldisplay/s/m/data";
URL obj = new URL(endpoint);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST"); // but maybe you want GET here...
con.setConnectTimeout(10000);
con.setDoInput(true);
con.setDoOutput(true);
JSONObject inputJSON = new JSONObject();
inputJSON.put("Client_id", 1);
inputJSON.put("Staff_id", 2);
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
OutputStream os = con.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(inputJSON.toString());
writer.flush();
writer.close();
os.close();
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response);
} catch (SocketTimeoutException se) {
// handle timeout exception
responseCode = -1;
} catch (Exception e) {
// handle general exception
responseCode = 0;
}
The only major change in adapting the above code for GET would be that you wouldn't write your input data to the connection. Instead, you would just append query parameters to the URL. I am possibly guessing that you need POST here, since your URL doesn't have any query parameters in it.

Trouble with "inputstream" when creating mobile app that downloads weather information (with AsyncTask)

I'm trying to make a mobile app that downloads info from the openweathermap.org apis. For example, if you feed that app this link: http://api.openweathermap.org/data/2.5/weather?q=Boston,us&appid=fed33a8f8fd54814d7cbe8515a5c25d7 you will get the information about the weather in Boston, MA. My code seems to work up to the point where I have to convert the input stream to a string variable. When I do that, I get garbage. Is there a particular way to do this seemingly simple task in a proper way? Here is my code so far...
private class DownloadWebpageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
try {
return downloadUrl(urls[0]);
} catch (IOException e) {
return null;
}
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
TextView test = (TextView) findViewById(R.id.test);
if(result!=null) test.setText(result);
else{
Log.i(DEBUG_TAG, "returned result is null");}
}
}
private String downloadUrl(String myurl) throws IOException {
InputStream is = null;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
int response = conn.getResponseCode();
Log.i(DEBUG_TAG, "The response is: " + response);
is = conn.getInputStream();
String text = getStringFromInputStream(is);
//JSONObject json = new JSONObject(text);
//try (Scanner scanner = new Scanner(is, StandardCharsets.UTF_8.name())) {
//text = scanner.useDelimiter("\\A").next();
//}
//Bitmap bitmap = BitmapFactory.decodeStream(is);
return text;
}catch(Exception e) {
Log.i(DEBUG_TAG, e.toString());
}finally {
if (is != null) {
is.close();
}
}
return null;
}
private static String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
Check this library . Is An asynchronous callback-based Http client for Android built on top of Apache’s HttpClient libraries.

Getting "Error parsing data org.json.JSONException: End of input at character 0 of" on reddit API

Hello I'm trying to use this endpoint www.reddit.com/reddits.json to show some list on android and I'm getting this error, below is my code.
I have this asynctask class on my main activity class:
private class AsyncListLoader extends AsyncTask<String, Integer, JSONObject>{
private JSONParser jsonParser = new JSONParser();
private static final String REDEEM_URL = "http://www.reddit.com/reddits.json";
private HashMap<String, String> param = new HashMap<>();
#Override
protected JSONObject doInBackground(String... params) {
JSONObject json = jsonParser.makeHttpRequest(REDEEM_URL, "GET", param);
if (json != null) {
Log.d("JSON result", json.toString());
return json;
}
else {
Log.d("JSON result", "is null");
}
return null;
}
#Override
protected void onPostExecute(JSONObject s) {
try {
if(!s.has("kind")){
Toast.makeText(MainActivity.this, "Something went wrong", Toast.LENGTH_LONG).show();
}
else {
JSONObject list = s.getJSONObject("data");
JSONArray childrens = list.getJSONArray("children");
for(int i = 0; i < childrens.length(); i++){
JSONObject o = childrens.getJSONObject(i).getJSONObject("data");
Feed f = new Feed(o.getString("icon_img"),o.getString("banner_img"),o.getString("display_name"));
MainActivity.this.adapter.add(f);
}
}
} catch (JSONException e){
e.printStackTrace();
}
}
}
makehttpRequest when get:
if(method.equals("GET")){
// request method is GET
if (sbParams.length() != 0) {
url += "?" + sbParams.toString();
}
try {
urlObj = new URL(url);
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(false);
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept-Charset", charset);
conn.setConnectTimeout(15000);
conn.connect();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
//Receive the response from the server
InputStream in = new BufferedInputStream(conn.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
Log.d("JSON Parser", "result: " + result.toString());
} catch (IOException e) {
e.printStackTrace();
}
conn.disconnect();
// try parse the string to a JSON object
try {
jObj = new JSONObject(result.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON Object
return jObj;
I tested out another json endpoints on the web and they are working. I dont have any idea why is this happening.
EDIT:
No param is being used so the url is fine.
The json is valid, I checked this in differents websites.

JSON retriving data from HttpURLConnection

I've been following a tutorial which provided an example website to use in the json request, however when i put in my own website to scrape data from, nothing happens.
Here is my code;
private TextView tvData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvData = (TextView) findViewById(R.id.tvJsonItem);
new JSONTask().execute("http://jsonparsing.parseapp.com/jsonData/moviesDemoItem.txt");
}
public class JSONTask extends AsyncTask<String,String, String>{
#Override
protected String doInBackground(String ... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("movies");
JSONObject finalObject = parentArray.getJSONObject(0);
String ChampionName = finalObject.getString("movie");
String mostGames = finalObject.getString("year");
return ChampionName + mostGames;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
tvData.setText(result);
}
}
}
Screen of when it works on left and screen when it doesnt work on right.
So yeah, this is what i know i have to change
new JSONTask().execute("http://api.champion.gg/champion/Ekko");
and
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("WHAT DO I PUT HERE");
JSONObject finalObject = parentArray.getJSONObject(0);
String ChampionName = finalObject.getString("WHAT DO I PUT HERE");
String mostGames = finalObject.getString("WHAT DO I PUT HERE");
From this URL - http://api.champion.gg/champion/Ekko/ , i want to get lets say the first two fields "key":"Ekko","role":"Top", so if anyone could give me a hand, that would be great!
According to the JSON returned form your link http://api.champion.gg/champion/Ekko/
You have to start to parse your string response as JSONArray
JSONArray parentObject = new JSONArray(finalJson);
then start to loop through this array to get JSONObject
JSONObject jsonObject = parentObject.getJSONObject(yourLoopIndex);
Inside each JSONObject you can get any value. by using the key in the original JSON string.

Need to change String into JSON and return it. The code runs fine except I get the error: java.lang.String cannot be converted to JSONObject

Everything seems to be fine except for the JSON exception error.
Here it is specifically: org.json.JSONException:
Value username of type `java.lang.String` cannot be converted to `JSONObject`.
There are a number of other flags that I can check in logcat and everything seems pretty good except that. I think the problem is that I need to convert the String encodedStr into a JSON object and return it to ASYNC TASK.
private class AsyncDataClass extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
//Use HashMap, it works similar to NameValuePair
Map<String, String> dataToSend = new HashMap<>();
dataToSend.put("username", params[1]);
dataToSend.put("password", params[2]);
//Server Communication part - it's relatively long but uses standard methods
//Encoded String - we will have to encode string by our custom method (Very easy)
String encodedStr = getEncodedData(dataToSend);
//Will be used if we want to read some data from server
BufferedReader reader = null;
//Connection Handling
try {
//Converting address String to URL
URL url = new URL(serverUrl);
//Opening the connection (Not setting or using CONNECTION_TIMEOUT)
HttpURLConnection con = (HttpURLConnection) url.openConnection();
//Post Method
con.setRequestMethod("POST");
//To enable inputting values using POST method
//(Basically, after this we can write the dataToSend to the body of POST method)
con.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
//Writing dataToSend to outputstreamwriter
writer.write(encodedStr);
//Sending the data to the server - This much is enough to send data to server
//But to read the response of the server, you will have to implement the procedure below
writer.flush();
//Data Read Procedure - Basically reading the data comming line by line
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while ((line = reader.readLine()) != null) { //Read till there is something available
sb.append(line + "\n"); //Reading and saving line by line - not all at once
}
line = sb.toString();//Saving complete data received in string, you can do it differently
//Just check to the values received in Logcat
Log.i("custom_check", "The values received in the store part are as follows:");
Log.i("custom_check", line);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close(); //Closing the
} catch (IOException e) {
e.printStackTrace();
}
}
}
//Same return null, but if you want to return the read string (stored in line)
//then change the parameters of AsyncTask and return that type, by converting
//the string - to say JSON or user in your case
**strong text**return encodedStr;**strong text**
**strong text**HERE IS THE PROBLEM I BELIEVE.
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
System.out.println("Resulted Value: " + result);
if (result.equals("") || result == null) {
Toast.makeText(MainActivity.this, "Server connection failed", Toast.LENGTH_LONG).show();
return;
}
int jsonResult = returnParsedJsonObject(result);
if (jsonResult == 0) {
Toast.makeText(MainActivity.this, "Invalid username or password", Toast.LENGTH_LONG).show();
return;
}
if (jsonResult == 1) {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
intent.putExtra("USERNAME", enteredUsername);
intent.putExtra("MESSAGE", "You have been successfully login");
startActivity(intent);
}
}
private int returnParsedJsonObject(String result) {
JSONObject resultObject = null;
int returnedResult = 0;
try {
resultObject = new JSONObject(result);
returnedResult = resultObject.getInt("success");
} catch (JSONException e) {
e.printStackTrace();
}
return returnedResult;
}
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = br.readLine()) != null) {
answer.append(rLine);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return answer;
}
//************getEncodedData*****************//
private String getEncodedData(Map<String,String> data) {
StringBuilder sb = new StringBuilder();
for(String key : data.keySet()) {
String value = null;
try {
value = URLEncoder.encode(data.get(key), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if(sb.length()>0)
sb.append("&");
sb.append(key + "=" + value);
}
return sb.toString();
}`enter code here`

Categories