Android : get data from MySQL using 'where' condition - java

I am trying to get data from MySQL database to my android app using where condition. I already create a method for get data. This method give me all data as a string array from a single column.
Look the bellow method :
String adress = "http://myserver_link/get_data.php";
InputStream inputStream = null;
String line = null, result = null, data[];
private void get_data(){
try {
URL url = new URL(adress);
HttpURLConnection httpsURLConnection = (HttpURLConnection) url.openConnection();
httpsURLConnection.setRequestMethod("GET");
inputStream = new BufferedInputStream(httpsURLConnection.getInputStream());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// read input stream into a string
try{
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
while ((line = bufferedReader.readLine()) != null){
stringBuilder.append(line + "\n");
}
inputStream.close();
result = stringBuilder.toString();
}
catch (Exception e) {
e.printStackTrace();
}
// Parse json data
try{
JSONArray jsonArray = new JSONArray(result);
JSONObject jsonObject = null;
data = new String[jsonArray.length()];
for (int i=0; i<jsonArray.length(); i++){
jsonObject = jsonArray.getJSONObject(i);
data[i] = jsonObject.getString("user_adress"); // column name
}
}
catch (Exception e){
e.printStackTrace();
}
}
This is my get data java method. And my get_data.php code is :
<?php
require "conn.php";
$query = mysqli_query($conn, "select * from android_data");
if ($query) {
while ($row = mysqli_fetch_array($query)) {
$flag[] = $row;
}
print(json_encode($flag));
}
$conn->close();
?>
Now I want to write my get_data.php file like bellow :
<?php
require "conn.php";
$user_name = $_POST["username"];
$query = mysqli_query($conn, "select * from android_data where username='$user_name'");
if ($query) {
while ($row = mysqli_fetch_array($query)) {
$flag[] = $row;
}
print(json_encode($flag));
}
$conn->close();
?>
But how I can send username using get_data() java method from my app?

You should probably send this as a parameter on the URL...
String adress = "http://myserver_link/get_data.php?username=xxxxx";
Not done Java for a while, but you can create this string using the appropriate value for xxxxx.
This will then be passed in as $_GET["username"] instead of $_POST["username"]. So just replace this line
$user_name = $_POST["username"];
with
$user_name = $_GET["username"];

Or you can change the Request method to POST in your Java code.

Related

Java app connection to MySQL with json no value for

Hi i have a problem with display data from my database on my app
That's part of Java file
#Override
protected String doInBackground(String... params)
{
String result ="";
String host = "http://192.168.0.12/LoginRegister/workelectricallist.php";
try
{
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(host));
HttpResponse response = client.execute(request);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer stringBuffer = new StringBuffer("");
String line = "";
while ((line = reader.readLine()) != null)
{
stringBuffer.append(line);
break;
}
reader.close();
result = stringBuffer.toString();
}
catch (Exception e)
{
return new String("There exception: " + e.getMessage());
}
return result;
}
#Override
protected void onPostExecute(String result)
{
try
{
Toast.makeText(getApplicationContext(),"1 enter", Toast.LENGTH_SHORT).show();
JSONObject jsonResult = new JSONObject(result);
int success = jsonResult.getInt("success");
if (success == 1)
{
Toast.makeText(getApplicationContext(),"2 enter", Toast.LENGTH_SHORT).show();
JSONArray ad = jsonResult.getJSONArray("ad");
for(int i=0; i < ad.length(); i++)
{
JSONObject object = ad.getJSONObject(i);
int id = object.getInt("id");
String user_name = object.getString("user_name");
String NameAd = object.getString("NameAd");
double Content = object.getDouble("Content");
String TypeOfAd = object.getString("TypeOfAd");
String line = id + "-" + user_name + "-" + NameAd + "-" + Content + "-" + TypeOfAd;
adapter.add(line);
}
}
else
{
Toast.makeText(getApplicationContext(),"No Ad to display", Toast.LENGTH_SHORT).show();
}
}
catch (JSONException e)
{
Toast.makeText(getApplicationContext(),e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
php file take data from MySQL data base, i can see array of data on a broswer
but on my app, i can see only "1 enter" and "no value for a success"
Like it didn't go to if, but there is no "No ad to display" so it didnt go to else
That's php file
<?php
$host ='localhost';
$user ='root';
$pwd ='';
$db ='loginregister';
$conn = mysqli_connect($host, $user, $pwd, $db);
if(!$conn)
{
die("Error in connection" . $mysqli_connect_error());
}
$response = array();
$sql_query = "select *from ad";
$result = mysqli_query($conn, $sql_query);
if(mysqli_num_rows($result) > 0)
{
$response['succes'] = 1;
$ad = array();
while ($row = mysqli_fetch_assoc($result))
{
array_push($ad, $row);
}
$response['ad'] = $ad;
}
else
{
$response['succes']=0;
$response['succes']='no data';
}
echo json_encode($response);
mysqli_close($conn);
?>
Using a local service you also need to see your development environment. If the app runs on the same machines where the site is hosted there should be no problem. If, on the other hand, the app is used externally, the error may be caused by the http request not being able to get a response because it does not know who to ask for the response.
I invite you to analyze the try and catch since there is the error "no value for a success". It is very likely that the result string do not get readed correctly or is not in a json format and because of that sends you the exception.
By googling "JSONException no value for" it possible to find extra information about this kind of issue like Android - JSONException No value for

I cant insert data from a java program to laravel app via api

I am new to laravel and I would like to save data to my online server via laravel api from a java program but I am getting errors.
this is my route on api.php:
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::post('hooks','ApiTestController#store');
my ApiTestController: its just handles POST request then saves to the table.
public function store(Request $request)
{
$postdata = json_decode($request->input('post_data'), true);
$datas = $postdata['header'];
$data = $datas[0];
$testH = new TestH();
$testH->test_date = $data['test_date'];
$testH->expiration = $data['test_date'];
$testH->source = $data['source'];
$testH->save();
return $testH;
}
and my java code :
try {
//local development server url
URL url = new URL("http://127.0.0.1:8000/api/hooks");
URLConnection con = url.openConnection();
// activate the output
con.setDoOutput(true);
PrintStream ps = new PrintStream(con.getOutputStream());
//create the JSON String
String json = null;
StringWriter sw = new StringWriter();
JSONWriter wr = new JSONWriter(sw);
try {
wr.object().key("header").array();
wr.object();
wr.key("test_date").value(new Date());
wr.key("source").value("TEST");
wr.key("expiration").value(new Date());
wr.endObject();
wr.endArray().endObject();
json = sw.toString();
System.out.println(json);
} catch (JSONException ex) {
Logger.getLogger(WebConnectSample.class.getName()).log(Level.SEVERE, null, ex);
}
// send to laravel server
ps.print("post_data="+json);
HttpURLConnection httpConn = (HttpURLConnection) con;
InputStream is;
if (httpConn.getResponseCode() >= 419) {
is = httpConn.getErrorStream();
} else {
is = httpConn.getInputStream();
}
// read the server reply
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
// close the print stream
}
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
the thing is when I dont save via $testH->save() everything works fine. but if I include it java returns with the following error:
Type error: Argument 1 passed to Illuminate\Routing\Middleware\ThrottleRequests::addHeaders() must be an instance of Symfony\Component\HttpFoundation\Response, string given, called in C:\Users\relixusdev\Documents\WebProjects\tcmsite\vendor\laravel\framework\src\Illuminate\Routing\Middleware\ThrottleRequests.php on line 61
any idea what part causes the error? does it have to do with authentication? i just want to be able to save to the online database via my java program.
Try using Route group with prefix as below
Route::group(['prefix' => 'api'], function() {
Route::post('hooks','ApiTestController#store');
});
if anyone comes here having the same problem, i found out that the problem is that I dont have the created_at and updated_at column at my table. I didn't realized its a requirement for laravel. silly me.

Json Parse not working properly but works on jsontest

I am a new programmer, i am trying to build an app with Json.
I created Json parser class and in my main activity i have the following code :
String url = "http://echo.jsontest.com/key/value/one/two";
JSONObject json = jParser.getJSONFromUrl(url);
one = json.getString(gridArray.get(lekeres).getTitle()); // one has the good value "two"
This works great. BUT
if i change url to : https://api.myjson.com/bins/3f8d2
which is exactly the same code as in the jsontest, one doesn't have "two" . I searched for hours but i don't know why this is happening. I did nothing but change the url. The contest is the same...
Since I don't know how is your parser. I made a quick test and can read both link normally with this code:
try {
//url = new URL(""http://echo.jsontest.com/key/value/one/two2");
url = new URL("https://api.myjson.com/bins/3f8d2");
InputStream is = url.openStream();
JSONObject json = null;
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
String jsonText = sb.toString();
json = new JSONObject(jsonText);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
This is more examples: http://en.proft.me/2013/12/5/how-parse-json-java/.
You can make your getJSONFromUrl similarly. Otherwise like other suggest try without https://.

URLConnection and POST method android

I am trying to make a post request using the reference of this documentation. But the problem is that the PHP developer at the other end is not able to receive the value of the parameter hence is not able to send a proper response. Am I missing something out here.
// Edits ;
I am making a HTTP Post request. As you can seen the code below. I am writing the arguments and parameters (location_id=3) to the outputstream. I have also pasted the code for PHP which i have been using. Now the problem is:
The parameter value ( which is 3 ) is not received at the PHP code so I am getting a response which is surrounded by the else block. So I just want to know if there is an error in the android code or the PHP code
#Override
protected Boolean doInBackground(String... params) {
Log.d(Constants.LOG_TAG,Constants.FETCH_ALL_THEMES_ASYNC_TASK);
Log.d(Constants.LOG_TAG," The url to be fetched "+params[0]);
try {
url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
// /* optional request header */
// urlConnection.setRequestProperty("Content-Type", "application/json");
//
// /* optional request header */
// urlConnection.setRequestProperty("Accept", "application/json");
/* for Get request */
urlConnection.setChunkedStreamingMode(0);
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setRequestMethod("POST");
List<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>();
nameValuePairs.add(new BasicNameValuePair("location_id",params[1]));
outputStream = urlConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
bufferedWriter.write(writeToOutputStream(nameValuePairs));
int statusCode = urlConnection.getResponseCode();
/* 200 represents HTTP OK */
if (statusCode == 200) {
inputStream = new BufferedInputStream(urlConnection.getInputStream());
response = convertInputStreamToString(inputStream);
Log.d(Constants.LOG_TAG, " The response is " + response);
return true;
}
else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(inputStream != null){
inputStream.close();
}
if(outputStream != null){
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
// Here is the code for writeToOutputStream
public String writeToOutputStream(List<BasicNameValuePair> keyValuePair)throws UnsupportedEncodingException{
String result="";
boolean firstTime = true;
for(BasicNameValuePair pair : keyValuePair){
if(firstTime){
firstTime = false;
}
else{
result = result.concat("&");
}
result = result + URLEncoder.encode(pair.getKey(), "UTF-8");
result = result + "=";
result = result+ URLEncoder.encode(pair.getValue(),"UTF-8");
}
Log.d(Constants.LOG_TAG," The result is "+result);
return result;
}
// Here is the code for convertInputStream to String
public String convertInputStreamToString(InputStream is) throws IOException {
String line="";
String result="";
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
while((line = bufferedReader.readLine()) != null){
Log.d(Constants.LOG_TAG," The line value is "+line);
result += line;
}
/* Close Stream */
if(null!=inputStream){
inputStream.close();
}
return result;
}
Here is the PHP CODE
<?php
include 'config.php';
header ('Content-Type:application/json');
if(isset($_POST['location_id']))
{
$id=$_POST['location_id'];
$selectThemeQuery = mysql_query("select theme_id from location_theme where location_id='$id'",$conn) or die (mysql_error());
$noRows = mysql_num_rows($selectThemeQuery);
//echo "HI";
if($noRows > 0)
{
$result = array();
while($row = mysql_fetch_assoc($selectThemeQuery))
{
$themeid = $row['theme_id'];
//echo "HI";
$selectNameQuery = mysql_query("select theme_name,theme_image from theme where theme_id='$themeid'",$conn) or die(mysql_error());
$numRows = mysql_num_rows($selectNameQuery);
if($numRows > 0)
{
while($rows = mysql_fetch_assoc($selectNameQuery))
{
$name = $rows['theme_name'];
$image = $rows['theme_image'];
$result[] = array('theme_id'=>$themeid,'theme_name'=>$name, 'theme_image'=>$image);
}
}
}
//echo json_encode($result);
echo json_encode("Hi");
}
else
{
$data2[] = array('Notice'=>false);
echo json_encode($data2);
}
}
else
{
echo "Not Proper Data";
}
?>
Remove:
urlConnection.setChunkedStreamingMode(0);
You use a buffered writer so it can only buffer instead of write.
To force all been written:
bufferedWriter.write(writeToOutputStream(nameValuePairs));
bufferedWriter.flush();
And then ask for a response code. And don't call a response code a status code.
writeToOutputStream() ??? What a terrible name. That function does not write to an output stream. It justs makes a text string.
For Android, I would suggest using a library like Spring-Android.
Spring-Android contains a RestTemplate class, which is a quite effective REST-Client. For example, a simple POST request would be...
myRestTemplate.exchange("http://www.example.net", HttpMethod.POST, new HttpEntity( ...some JSON string ...), String.class );
To create the JSON String, I suggest a library like Jackson, which should work fine on Android, see for example here. Not sure if Jackson integrates as fine in Spring-Android as it does in Spring-Web, but in any case, using it to create the Json Strings manually should work just fine.
for post method
create a string builder first
StringBuilder strbul=new StringBuilder();
then append the data like
strbul.append("name=sangeet&state=kerala");
then write to output stream like
httpurlconnection.getOutput().write(strbul.toString().getBytes("UTF-8"));
php script will recieve that data on
$_POST['name'] and $_POST['state']

Cannot parse JSON to Java(android)

My PHP file:
<?php
include("ConnectDatabase.php");
$Username = mysql_real_escape_string($_POST['Username']);
$Password = mysql_real_escape_string($_POST['Password']);
$q = mysql_query("SELECT Username, Password FROM Users
where Username = '".$Username."' and
Password = '".$Password."'", $con);
if(mysql_num_rows($q) > 0){
$row = mysql_fetch_assoc($q);
print json_encode($row);
}else{
print "0";
}
?>
I tried to parse that by the following to get a value,but it got null values both userJson and passJson:
public void parseJson(String result){
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
userJson = jArray.getJSONObject(i).getString("Username").toString();
passJson = jArray.getJSONObject(i).getString("Password").toString();
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
Anyone can see my mistake ? Thank you
PS This is my older post that related to this post.
I would think they end up null cuz the first line doesn't work. It's not a JSONArray as you have generated.
try {
JSONObject root = new JSONObject(result);
username = root.getString("Username");
password = root.getString("Password");
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
something like that.

Categories