Hi I'm about to perform an HTTP request to add some data to a local data base using wampserver, so I've made a button andh within that button i will perform that action , but the problem is that i can't connect to the data base !!!
this is the message apperas on the toast "android.os.networkonmainthreadexception"
and this is my code ---> http://pastebin.com/TsQ7NbNm
============================
I'm Newer to Android Programming so please Help me !
You cannot make http request on your UI thread. Consider using AsyncTask or some other method of asynchronuos call.
Upto the API level-10 it is fine to make http request on UI thread. But from API-11, any task that takes long time to complete must be done on background task. The reason behind this is any task that takes 5 seconds or more on UI thread then ANR(Application Not Responding) i.e. force close happens. To do that we have create some background thread or simply make use of AsyncTask.
if you want to post data on your server then you need to well design server for post data. recent my server configuration i post data by using this code and well performed.
Button send = (Button) findViewById(R.id.send_sms);
send.setOnClickListener(this);
public void onClick(View v)
{
switch (v.getId())
{
case R.id.send_sms:
try {
HttpClient client = new DefaultHttpClient();
String postURL = "http://10.0.2.2/folder/saver.php";
HttpPost post = new HttpPost(postURL);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("cell", "+8801899999"));
params.add(new BasicNameValuePair("pin", "1234"));
params.add(new BasicNameValuePair("msg", "hi!"));
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
post.setEntity(ent);
HttpResponse responsePOST = client.execute(post);
HttpEntity resEntity = responsePOST.getEntity();
if (resEntity != null) {
showAlert(EntityUtils.toString(resEntity));
//Log.i("RESPONSE",EntityUtils.toString(resEntity));
}
} catch (Exception e) {
e.printStackTrace();
}
break;
}
}
you can try this way.if your server has password then give it.
<?php
mysql_connect("localhost","root","");
mysql_select_db("test");
$valeur1=$_REQUEST['valeur1'];
$valeur2=$_REQUEST['valeur2'];
$req=mysql_query("insert into testapp (valeur1,valeur2) values('$valeur1','$valeur2')");
if($req)
echo "ok";
else
echo "erreur";
;
?>
Related
So i'm a web developer by trade but am making an app at the moment.
I've got a program on my PC which sends data from my PC to a database on my webhost.
What I'm after now, is to create an app that is able to download that data with a series of queries.
Are there any good resources around that would help me to develop some Java code, to connect to a server through my tablet when I'm out and about and download the information from my webhost when on a different wifi network?
Thanks chaps, any help is appreciated.
The way I handle it is that I just create a web page based on what I want to do. For example if I want to verify a login on an app I create a page that takes in a username and password.
On the device I just post the username and password values by using a HTTP post transaction.
Example:
public boolean LoginUser()
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("your URL comes here...");
try
{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
DataCrypt crypt = new DataCrypt();
try
{
this.Cryptemail = crypt.bytesToHex(crypt.encrypt(this.Email));;
this.Cryptpass = crypt.bytesToHex(crypt.encrypt(this.Password));
}
catch (Exception e)
{
DebugLog.log(e.getMessage());
}
nameValuePairs.add(new BasicNameValuePair("Password", this.Cryptpass));
nameValuePairs.add(new BasicNameValuePair("Mail", this.Cryptemail));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
BasicHttpResponse response = (BasicHttpResponse) httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String response = EntityUtils.toString(entity);
return true;
}
catch (Exception e)
{
DebugLog.log(e.getMessage());
return false;
}
return false;
}
EDIT: So you can just make a page that takes in some parameters that you want to base your query on and return the result in some way (for example by XML).
Hope this helps you out! :)
i want to connect my android app to my servlet site ,, that i need to pass some data from the app to the url
Can anyone help me?
I have written this code to pass two parameters but it generates an exception:
HttpPost postMethod = new HttpPost("http://androidsaveitem.appspot.com/view");
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("description+", "HAANAA"));
formparams.add(new BasicNameValuePair("id+", "11223"));
UrlEncodedFormEntity entity;
entity = new UrlEncodedFormEntity(formparams);
postMethod.setEntity(entity);
DefaultHttpClient hc = new DefaultHttpClient();
HttpResponse response = hc.execute(postMethod);
it seems that you are blocking the UI thread , and ANR Exception is raised since if your UI Thread is blocked for 5 second this exception will occur , to come over this issue you can use Thread or AsyncTask to do the job ,so your UI thread don't get blocked
example :
public myAsnyc extends AsyncTask<Void, Void,Void>{
protected void doInBackground(){
HttpPost postMethod = new HttpPost("http://androidsaveitem.appspot.com/view");
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("description+", "HAANAA"));
formparams.add(new BasicNameValuePair("id+", "11223"));
UrlEncodedFormEntity entity;
entity = new UrlEncodedFormEntity(formparams);
postMethod.setEntity(entity);
DefaultHttpClient hc = new DefaultHttpClient();
HttpResponse response = hc.execute(postMethod);
}
protected void onPostExecute(){
log.d("myApp", "success");
}
}
and if you want to execute it
make this call
new myAsnyc().execute();
if you want to update the UI elements use the onPostExecute() method and modify the generic type of the async task
UPDATE
execute the following code
use this code
try {
InetAddress i = InetAddress.getByName("http://androidsaveitem.appspot.com/view");
} catch (UnknownHostException e1) {
e1.printStackTrace();
}
before you call the async task
if the exception occur fine , re run the app second time it will run normally
What I try to do
Hello Guys,
I try to create a login for my server, that I can access the data on it over my app. For this i created a Methode called 'public void doLogin(final String username, final String password)' . In this Methode I start a Thread in which I post the username and password to my server. Now to problem starts. When I do the post my server can't handle my post which looks like this: '"username="+username+"&password="+password'.
To try if its a serverside problem (infact its not) I made a post over 'curl -d' with the same parameters and I get a response without any problems.
For your information the server runs on Ruby3
Question
How do I need to change my Post to the server that it can handle the data I send. By the way the string I post must look exactly like that: '"username="+username+"&password="+password //this means username=LEUSER&password=LEPASS'
Please tell me what I need to change, some code snippets or tutorials would be great. Down here you find the importrent codesnippets of the doLogin Methode
Code
public void doLogin(final String username, final String password) {
Thread t = new Thread() {
public void run() {
String URL = "http://192.168.110.126:3000/sessions.json"; //für momentane testzwecke
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse response;
try {
HttpPost post = new HttpPost(URL);
StringEntity se = new StringEntity("username="+username+"&password="+password);
post.setEntity(se);
response = client.execute(post);
if (response != null) {
//response handling
handler.sendEmptyMessage(0);
}
} catch (Exception e) {
e.printStackTrace();
Log.e("DataHandler", "URLConnection-Error" + e);
}
}
};
t.start();
}
Please Guide me Regarding This.
Your code looks like you are sending a html form. In fact curl adds a content-type (with value application/x-www-form-urlencoded) to the http header if you use the -d option.
So try to add the header field like this:
HttpPost post = new HttpPost(URL);
post.addHeader("Content-Type","application/x-www-form-urlencoded");
...
What you need to change is the String entity part. You should change with the following;
ArrayList<NameValuePair> requestParameters = new ArrayList<NameValuePair>();
requestParameters.add(new BasicNameValuePair("username", username));
requestParameters.add(new BasicNameValuePair("password", password));
username & password are the variables that are input on the program.
Lastly, if you forget to set permission it also won't work. You need to set android.permission.INTERNET
I'm trying to increase my knowledge to Android and trying to code a small app for my personal needs.
I'm trying to post data via the HTTP Post method on a test server.
The request is sent ok, but now, I'm trying to display the response, which is an HTML page with the dump of my request.
Here is an extract of my code, it is basically a few EditText fields, and button that sends the request.
The following code is the listener for that button.
validateButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://posttestserver.com/post.php?dump&html&dir=mydir&status_code=200");
try {
// Gathering data
String value01 = nb01Spinner.getSelectedItem().toString();
String value02 = nb02EditText.getText().toString();
String value03 = nb03EditText.getText().toString();
String value04 = nb04EditText.getText().toString();
// Add data to value pairs
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(04);
nameValuePairs.add(new BasicNameValuePair("test01", value01));
nameValuePairs.add(new BasicNameValuePair("test02", value02)); //
nameValuePairs.add(new BasicNameValuePair("test03", value03));
nameValuePairs.add(new BasicNameValuePair("test04", value04));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
I'm not sure if I need to create another Activity or not... I suppose I also have to create a webview aswell, but I'm a bit lost. For now the "raw" HTML would be fine, but afterwards I will need to parse the data, and extract only the strings I need.
So I would need help (an a good and simple example !)
Thank you.
String ret = EntityUtils.toString(response.getEntity());
Maybe this will help?
Very simple approach is Take textview the way you have taken button widget. and what ever response you got set in the textview. you will be able to see the response. else use the Log to log your response in the logcat.
This is how you get the Http response :
byte[] buffer = new byte[1024];
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://www.rpc.booom.com");
postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("params","1"));
//.......
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
HttpResponse response = httpclient.execute(httppost);
Log.w("Response ","Status line : "+ response.getStatusLine().toString());
buffer = EntityUtils.toString(response.getEntity()).getBytes();
I am using:
Log.d("log_response", response.getStatusLine().toString());
I'm developing an Android app that gets a JSON_encoded result from a php middleware script that connects to a MySQL database. I have given the application Internet permissions.
The problem I'm having is that the program gives an UnknownHostException error the first time it is run. I have the program on a timer, and subsequent calls to the timer handler function do not return the UnknownHostException error. Do you have any idea why this would occur? I have tested the domain and made sure that it connects correctly through a web browser.
Here's a snippet from the code:
public final void timerAlert(){
final Handler handler = new Handler();
final Runnable r = new Runnable()
{
public void run() {
Timer_Method();
handler.postDelayed(this,1000);
}
};
handler.postDelayed(r, 1000);
}
public void Timer_Method()
{
//See if this buzzer is being signaled.
String result = null;
InputStream is = null;
StringBuilder sb=null;
//http post
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("BuzzerID",BuzzerID.toString()));
Toast.makeText(getBaseContext(), "BuzzerID="+BuzzerID.toString() ,Toast.LENGTH_LONG).show();
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://domain/getBuzzStatus.php?BuzzerID="+BuzzerID.toString());
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection"+e.toString());
Toast.makeText(getBaseContext(), "Hm, problem here="+e.toString() ,Toast.LENGTH_LONG).show();
}
Note that domain has something else there in the actual code and that this is just a snippet but is where the first issue occurs. Also note that I am mixing get and post, something I'd rather not do, but for some reason passing the nameValuePair to the php script doesn't send anything to $_REQUEST.
A snippet from the very simple PHP script:
$sql_string="SELECT Signal FROM BuzzCustomer WHERE idBuzzCustomer=" . $_GET['BuzzerID'];
$sql = mysql_query($sql_string);
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));
mysql_close();
I switched to $_GET here because I could not get $_REQUEST to work. Any help would be appreciated. Thanks in advance!
May be their will be no Internet connection in the simulator......Check a url in browser
Instead of
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Use
ResponseHandler<String> response = new BasicResponseHandler();
String result = httpclient.execute(httppost,response);
Also put Internet permission in the Manifest
Just a guess, but maybe the DNS request takes too long and your HttpClient gives up, but the request is finished and cached so the next time it does not fail?
This With Apache HttpClient, why isn't my connection timeout working? seems to be a question about how to set the timeout for HttpClient.