yashsingh1/xdaforums huggingface dataset:
[Java for Android App Development] stekarson:
[Quoth E=dbarrera;42990815]Can you post your php code?

PHP code:

<?php

#Ensure that the client has provided a value for "FirstNameToSearch"
if (isset($_POST["FirstNameToSearch"]) && $_POST["FirstNameToSearch"] != ""){

#Setup variables
$firstname = $_POST["FirstNameToSearch"];

#Connect to Database
$con = mysqli_connect("localhost","root","ZD#myUALF75vo^4!01jAg$O2^pWIVr", "mytestdatabase");

#Check connection
if (mysqli_connect_errno()) {
echo 'Database connection error: ' . mysqli_connect_error();
exit();
}

#Escape special characters to avoid SQL injection attacks
$firstname = mysqli_real_escape_string($con, $firstname);

#Query the database to get the user details.
$userdetails = mysqli_query($con, "SELECT * FROM users WHERE FirstName = '$firstname'");

#If no data was returned, check for any SQL errors
if (!$userdetails) {
echo 'Could not run query: ' . mysqli_error($con);
exit;
}

#Get the first row of the results
$row = mysqli_fetch_row($userdetails);

#Build the result array (Assign keys to the values)
$result_data = array(
'FirstName' => $row[1],
'LastName' => $row[2],
'Age' => $row[3],
'Points' => $row[4],
);

#Output the JSON data
echo json_encode($result_data);
}else{
echo "Could not complete query. Missing parameter. YOLO!";
}
?>

Permissions:

simon@tuxflux8:/var/www/clientservertest$ ls -ls login.php
4 -rw-r--r-- 1 simon www-data 1282 Jun 27 15:26 login.php

Thanks for fiddling! ^^
[Java for Android App Development] nikwen:
There is PHP syntax highlighting: http://xdaforums.com/misc.php?do=bbcode#php

Would make it much easier to read. Just a suggestion. ;)
[Java for Android App Development] dbarrera:
[MENTION=1974034]stekarson[/MENTION] probably some characters from the password aren't being recognized... Have you tried by changing the password to only alphanumeric characters?

---------- Post added at 11:12 AM ---------- Previous post was at 11:10 AM ----------

Just in case, [MENTION=4553333]Alkonic[/MENTION] you can add to the op that for debugging, you can replace POST with GET and send parameters through url... And when working correctly, change them back to POST...
[Java for Android App Development] alobo:
Sounds like a good idea, I'll write up some more debugging tips and update the main post.

I also think you're right with the password. Additionally, [MENTION=1974034]stekarson[/MENTION], try using a simpler password for testing (something like: 'password').
[Java for Android App Development] stekarson:
Changing the password to a more simple one fixed it. Thanks! I used the following line to change the password:

$ mysqladmin -u root -p'oldpassword' password newpass
[Java for Android App Development] dbarrera:
Yeah, your password had the $ character which for php is the variable declaring character...

[MENTION=4553333]Alkonic[/MENTION] tonight I will try to separate the DoPOST class from the activity... This should help the code be reused for other activities within the same app (if needed)...
[Java for Android App Development] deniel:
Why if i run the application it just let me run it on the emulator and doesnt let me to it on my android?

I tryed other project and let me do it. On the left bottom corner it reconize but xperia arc s but with this app it doesnt, it suggets me to create an emulator.

I have an xperia arc S with a modded 4.2.2

I've setted current sdk api 17 and lower 8.
[Java for Android App Development] dbarrera:
Have you tried changing the url? http://10.0.2.2 is only for emulator...
[Java for Android App Development] deniel:
I uploaded the stuff on a web-host (altervista.org) cause ill have to show it without my computer, so i wont have my Apache server and my Emulator.

So in the HttpPost i passed my web-hosted-page as a parameter

or you mean something ese that i missunderstood?
[Java for Android App Development] dbarrera:
Have you confirmed that your Web service works correctly in that host?
[Java for Android App Development] deniel:
Yes, with the emulator works. The problem is that it doesnt allow me to run it on my real Android, it just let me run it on the emulator.

When i press Run it doesnt ask me on which device i want to run it, it just make me create an emulator

EDIT: i wrote again the application from 0 and now seam there are no problem.
[Java for Android App Development] metzzarn:
Thanks Alkonic! Great tutorial! :)

I have a problem when trying to connect to the server, getting connection refused. This is only if I use the app, when I use my browser on my phone, which is connected to my wireless, I get the "Could not complete query. Missing parameter" message.

Any ideas?

Have you enabled USB Debugging on your device?
[Java for Android App Development] alobo:
Could you double check if you have the Internet permission in your manifest? I'm 99% sure I forgot to include it in the update. :banghead:

<uses-permission android:name="android.permission.INTERNET" />
[Java for Android App Development] metzzarn:
Thats it!

Works like a charm! :)

Thanks!
[Java for Android App Development] Exikle:
For the

HttpPost httppost = new HttpPost("http://192.168.1.112/clientservertest/login.php");

instead if the internal ip, could it be possible to use your external?
[Java for Android App Development] alobo:
I looked through your code and downloaded your test data. I found that the code you use to create and read the JSONArray read the array is fine! In fact, your problem appears to be the 'resMessage' array - it's never initialized in your code! As a result, the code to retrieve the json data works, but it tries to store the data into a null array - that's why you get a NullPointerException.

Try initializing all your arrays:

String[] resUser = new String[50];
String[] resMessage = new String[50];
String[] resDate = new String[50];

For future use, I would recommend switching these arrays to some form of List - it makes dealing with variable sizes of data much easier.
[Java for Android App Development] alobo:
Yes, you can - you'd just have to setup appropriate port forwarding and take the security risks into account.
[Java for Android App Development] deniel:
Im used to PHP i guess xD and how can i set the dimension if i dont know how much big it will be? Ill try with List then next time thnk :) one last thing if its not a problem:

RelativeLayout layout = (RelativeLayout)findViewById(R.id.rl);
for(int i = 1; i <= count; i++)
{
final TextView textViewUtente = new TextView(mContext);
final TextView textViewMessaggio = new TextView(mContext);
final TextView textViewData = new TextView(mContext);
textViewUtente.setText(sepUser[i]);
textViewMessaggio.setText(sepMessage[i]);
textViewData.setText(sepDate[i]);
int curTextViewIdUtente = 1000+i;
int curTextViewIdMessaggio = 2000+i;
int curTextViewIdData = 3000+i;
textViewUtente.setId(curTextViewIdUtente);
textViewMessaggio.setId(curTextViewIdMessaggio);
textViewData.setId(curTextViewIdData);
final RelativeLayout.LayoutParams params =
new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);

params.topMargin= 100+i*150;

textViewUtente.setLayoutParams(params);
layout.addView(textViewUtente, params);

params.topMargin= 250+i*150;

textViewMessaggio.setLayoutParams(params);
layout.addView(textViewMessaggio, params);

params.topMargin= 100+i*150;
params.rightMargin=200;
textViewData.setLayoutParams(params);
layout.addView(textViewData, params);
}

i need to create X number of text view. I create 3 text view every for loop.

One with the user name, on his right the date and above the message. they technically create a "post" from the user on the blog.

Im able to make one post under the other but the date, message and username of every single postare all stuck one on top of the other.

I know this may not be the best way but i have to do this just to show the example sooner as possible.

i also tried with addRoles and .ABOVE and thing like that but nothing changes
[Java for Android App Development] dbarrera:
[MENTION=2995066]deniel[/MENTION] try ListView... You can store the data in an internal database, create a custom view, associated with the ListView which takes care of the amount of views needed...
[Java for Android App Development] deniel:
But im already able to create how much i need like this, i just need to place them in the righ place, every loop i need to place 3 TextView like this:

+--------------------+ +--------------------+

| textViewUser | | TextViewDate|

+--------------------+ +--------------------+

+--------------------+

| TextVewMess |

+--------------------+

Im able to make them but they are all one on top of the other.

But the loop after with the code the next 3 view go above the 3 before, but still all 3 one on top of the other.
[Java for Android App Development] dbarrera:
[MENTION=2995066]deniel[/MENTION] I understand the effort you've done in your code, but check this out: https://github.com/dbarrerap/CardMa...n/java/org/dbarrera/cardmanager/CardShow.java

Check also the res folder to see more clearly the mapping done in the code...

Good luck!
[Java for Android App Development] deniel:
I've trued with a listView and it worked. only problem is that i have to hide the keyboard to refresh the UI, cant udnerstand why :s but not abig deal
[Java for Android App Development] dbarrera:
Do you have an EditText view in the layout? Check if it has the tag <requestFocus /> and delete it... Maybe that can help...
[Java for Android App Development] gkohne:
JSONException

Hi ,

i keep gettign the following error :

org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject

this is from the original files - no changes made - is there something im doing wrong ?

Regards,

Glenn .
[Java for Android App Development] dbarrera:
echo <br /> is badly written... Check php file...
[Java for Android App Development] photonxda:
[MENTION=4553333]Alkonic[/MENTION] Nice , it is very helpful to me, Thanks for your code

I had clicked the thanks and then why couldn't I find your post in my forum's Profile ---- STATISTICS ---- Find all thanked posts by me ?
[Java for Android App Development] dbarrera:
[MENTION=4553333]Alkonic[/MENTION] if you dont mind, can I translate and expand upon your guide here? Credits to you will be mentioned and link to here will be provided...
[Java for Android App Development] alobo:
[MENTION=4423995]dbarrera[/MENTION] Go ahead!

[MENTION=5231470]photonxda[/MENTION] Glad you like the guide!
[Java for Android App Development] dbarrera:
guide has been translated (Spanish), extended and published: http://dbarrerap.github.io/android/development/database/2013/07/23/android-y-web-services.html
[Java for Android App Development] alobo:
Wow that's awesome! Thanks for translating :)
[Java for Android App Development] mariaaaaaaaa:
postman message

I followed the tutorial but I received this message

Could not get any response

This seems to be like an error connecting to localhost/clientservertest/login.php. The response status was 0.

Check out the W3C XMLHttpRequest Level 2 spec for more details about when this happens.

instead of this message

{"FirstName":"John","LastName":"Doe","Age":"25","Points":"61"}

pliiiiiiiiiiiz help me
[Java for Android App Development] alobo:
This seems to be a local server problem. Can you verify that your wamp server is up and running (try accessing localhost in your browser). If it's up, double check your for paths and ensure that the login.php is in the correct directory.
[Java for Android App Development] mariaaaaaaaa:
Yes it's a local server problem Thank you very much for your help :highfive:
[Java for Android App Development] Aroeris:
Some help and question

Hello, thanks for your tutorial you are the only one who made something simple with explanations !

But there are few things i do not understand could you explains please the purpose of

ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("FirstNameToSearch", strNameToSearch));

In your case you associate "firstNameToSearch" with the value to search right ? But if there were nothing to search for should we still use this for something ? And how the http block should be modified ?

I have tried to adapt your code to mine, I am trying to simply read a json array from my php file.

I do not use post variable etc, should I use still the httppost object ?

Moreover what is

<String, Void, Boolean>

in

public class DoPOST extends AsyncTask<String, Void, Boolean>{

?

I do not find the meaning and importance of it in the documentation.

Sadly my app crashes when i try to open the activity concerned by this :crying:

Thank you !
[Java for Android App Development] alobo:
If you are not sending parameters, you can simply remove the line

httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

Your HTTP block would look like this:

//Create the HTTP request
HttpParams httpParameters = new BasicHttpParams();

//Setup timeouts
HttpConnectionParams.setConnectionTimeout(httpParameters, 15000);
HttpConnectionParams.setSoTimeout(httpParameters, 15000);

HttpClient httpclient = new DefaultHttpClient(httpParameters);
HttpPost httppost = new HttpPost("http://192.168.1.6/clientservertest/login.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();

String result = EntityUtils.toString(entity);

//And so on

In regards to your other question regarding the AsnycTask, check out this link in the Android documentation. You'll specifically want the section titled "AsyncTask's generic types". Essentially, I am subclassing the AsyncTask for use in the demo. This overrides the AsyncTask's methods. I don't use this feature properly in this demo, as I simply copied and pasted the AsyncTask code from another project. I will look at simplifying it in a future release.

If you still encounter errors, please post them. If you app is still crashing, please post a logcat so I can help you diagnose the problem.

Hope this answers your questions, and glad you like the guide!
[Java for Android App Development] Sandeep_Jagtap:
Very Nice Post OP !!!!

Its real great to see you are sharing your knowledge !!!

One request here that will extend this tutorial

Could you possible tell how we can make same scenario on paid server ?

currently its on WAMP server.

What additionly we need to do ,if we want app to be on paid server ?

like domainName buying and buying server space ,creating database and php scripts .

I know its beyond the scope of android app but the necessary one to real world android app.

Thanks again.!!

looking forowrd for your future tutorial !!
[Java for Android App Development] super-b0y:
i got this error and i mean clueless. can you help me?

the error show up in toast when i click getdata

Value<!DOCTYPE of type java.lang.String cannot be converted to JSONObject
[Java for Android App Development] dbarrera:
It seems the response getting by the web service it's not a json response... before casting into jSONObject, print the response and check it out (System.out.println)...
[Java for Android App Development] super-b0y:
may i ask you a quick question, if i were to try using emulator or donwload his project to my app, which ip address should i choose?
[Java for Android App Development] super-b0y:
thank you. i manage to solve it already =)
[Java for Android App Development] alobo:
I'll add a section! It'll take a few days though.
[Java for Android App Development] alobo:
You're correct - from your logcat, it is crashing on line 104 with a NullPointerException:

tID.setText("ID : " + myUser.getID());

There are two things that could be causing it:

tID is null

mUser is null

The easiest thing to do is this:

int id = myUser.getID();
tID.setText("ID : " + id);

Split the assignment into two statements - it will allow you to find which object is null. If the TextView is null, it is an easy fix - you've probably not set the activity's layout properly, or have searched for the wrong id in findViewById().

If mUser is null, you will want to look through the code you use to create it - something could not be working there:

catch (Exception e)
{
Log.e("ClientServerDemo", "Error:", e);
exception = e;
}

Try commenting out that try/catch block to see if an error is thrown.

Hope this helps!
[Java for Android App Development] Aroeris:
You mean something like this ?

protected void onPostExecute(Boolean valid)
{
//Update the UI
try
{
int id = myUser.getID();
tID.setText("ID : " + id);
/*tGender.setText("Gender : " + myUser.getGender());
tAge.setText("Age : " + myUser.getAge());
tOccupation.setText("Occupation : " + myUser.getOccupation());*/
}
catch (Exception e)
{
Log.e("UserActivity", "Error:", e);
exception = e;
}

if(exception != null)
{
Toast.makeText(mContext, exception.getMessage(), Toast.LENGTH_LONG).show();
}
}

It doesn't change anything,

I believe there is also an issue with the toast.makeText.

I have checked my textviews there all declared like you so it should work :p

I have checked the name id etc everything seems fine, i really don't get it !

Is it possible that I am not doing something in the async class and in the block when calling it ? because i have removed few lines that you used and that i think were not useful for me.
[Java for Android App Development] dbarrera:
Is the class User declared? myUser variable instantiate the User class...

Just a heads up, getUserInfo sound more like a method than an actual class for your need... And according to this logic, User should be the class and within it define the getUserInfo which is called in the onPostExecute method... In a recent project I have something pretty much alike what you're trying to achieve, you can check it at http://github.com/dbarrerap/SIADU. Look for StudentActivity...
[Java for Android App Development] russellhoff:
Great post!! I have developed a Restful Web Service using JSON as communication media (also i've developed an Android app plus a backend, written in html5, css3, javascript and so on, but no server-side code).

For those who are used to Java, I recommend using Jersey framework.

Jersey framework let you implement Web Services written in Java. It's very simple to make a WS work.

For more information, visit jersey's official page (here: http://jersey.java.net/) or this awesome site, with excellent tutorials (here: http://www.vogella.com/articles/REST/article.html).
[Java for Android App Development] super-b0y:
can i just check with you, in your php code there is this like saying fetching the first row

#Get the first row of the results

$row = mysqli_fetch_row($userdetails);

may i just check what if i want to get more row. Because i have like 2 person with the same first name. i would like to display two result.

pls advise.
[Java for Android App Development] Aroeris:
Yes yes User is correctly define, the problem doesn't seem to come from there, somehow i cannot set the text of the textview ....

I though it was because i was not callingproperly the thread but after adding

GetUserInfo myThread = new GetUserInfo(UserInfoActivity.this);
myThread.execute();

and adding the constructor

GetUserInfo(Context context)
{
mContext = context;
}

I thought it would help but nop . Should i do something else with the context inside the thread ?
[Java for Android App Development] Aroeris:
So i found the error .... I was not selecting the correct layout in

setContentView(R.layout.activity_user_info);

This drove me crazy !
[Java for Android App Development] alobo:
Ahh I had a feeling it was something like this. I've made the same mistake many times :)
[Java for Android App Development] ss1w:
Question

Hi vijai2011, just wondering how exactly did you solv you null problem. I am pretty new at this thus i am not too sure what line or where should i make the adjustment.

Cheers
[Java for Android App Development] vijai2011:
I just commented out this line:

$firstname = mysqli_real_escape_string($con, $firstname);

by "#" and it worked
[Java for Android App Development] ss1w:
This is what i have done so far and i am having some difficulty fixing it.

<?php

#Ensure that the client has provided a value for "FirstNameToSearch"
if (isset($_POST["FirstNameToSearch"]) && $_POST["FirstNameToSearch"] != ""){

#Setup variables
$firstname = $_POST["FirstNameToSearch"];

#Connect to Database
$con = mysqli_connect("localhost","root","", "unnamedwifistrengthvisualisation");

#Check connection
if (mysqli_connect_errno()) {
echo 'Database connection error: ' . mysqli_connect_error();
exit();
}

#Escape special characters to avoid SQL injection attacks
$firstname = mysqli_real_escape_string($con, $firstname);

#Query the database to get the user details.
$userdetails = mysqli_query($con, "SELECT * FROM wifi WHERE WifiMacAddress = '$WifiMacAddress'");

#If no data was returned, check for any SQL errors
if (!$userdetails) {
echo 'Could not run query: ' . mysqli_error($con);
exit;
}

#Get the first row of the results
$row = mysqli_fetch_row($userdetails);

#Build the result array (Assign keys to the values)
$result_data = array(
'WifiMacAddress' => $row[0],
'WifiSSID' => $row[1],
'WifiLatitude' => $row[2],
'WifiLongtitude' => $row[3],
'WifiLocation' => $row[4],
);

#Output the JSON data
echo json_encode($result_data);
}else{
echo "Could not complete query. Missing parameter";
}
?>
[Java for Android App Development] vijai2011:
The code should be:

<?php

#Ensure that the client has provided a value for "FirstNameToSearch"
if (isset($_POST["FirstNameToSearch"]) && $_POST["FirstNameToSearch"] != ""){

#Setup variables
$firstname = $_POST["FirstNameToSearch"];

#Connect to Database
$con = mysqli_connect("localhost","root","", "unnamedwifistrengthvisualisation");

#Check connection
if (mysqli_connect_errno()) {
echo 'Database connection error: ' . mysqli_connect_error();
exit();
}

#Escape special characters to avoid SQL injection attacks
#$firstname = mysqli_real_escape_string($con, $firstname);

#Query the database to get the user details.
$userdetails = mysqli_query($con, "SELECT * FROM wifi WHERE WifiMacAddress = '$WifiMacAddress'");

#If no data was returned, check for any SQL errors
if (!$userdetails) {
echo 'Could not run query: ' . mysqli_error($con);
exit;
}

#Get the first row of the results
$row = mysqli_fetch_row($userdetails);

#Build the result array (Assign keys to the values)
$result_data = array(
'WifiMacAddress' => $row[0],
'WifiSSID' => $row[1],
'WifiLatitude' => $row[2],
'WifiLongtitude' => $row[3],
'WifiLocation' => $row[4],
);

#Output the JSON data
echo json_encode($result_data);
}else{
echo "Could not complete query. Missing parameter";
}
?>
[Java for Android App Development] ss1w:
Doesnt seems to work as well. Just to verify, my key would be FirstNameToSearch ?
[Java for Android App Development] vijai2011:
yes. The key is correct. Then i suppose you have problem somewhere else. Anyway mysqli is now deprecated and soon will be removed in the next php. So its better to use PDO but I too dont know much php. So I have to learn it soon.
[Java for Android App Development] ss1w:
Hi Vija2011, I have managed to get it work. Apparently i have been targeting the wrong table all these while. Cheers. Just a quick question does it work the same way updating the table ?
[Java for Android App Development] vijai2011:
You can update the table if you know mysql. Here is a example of how to insert a new row:

INSERT INTO `users`(`name`, `password`) VALUES ('vijai','mypass')

will insert the field name and password in the table user with the values vijai and mypass.

You can do this via the given php by altering the

#Get the user details from the database

line.
[Java for Android App Development] dubliner21:
Hi,

After running the attached code I am getting the error below.

"org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject"

I understand this may be a Php issue, but I have not made any changes to the code.

Any suggestions as to what the prob is ?

Cheers Dubliner