I'm so close to solving the phpMyAdmin connection, but still after onclicked nothing has happend, no error, no freeze. What is wrong here? Or maybe in my PHP code?
final String suma = Float.valueOf(zam.getSuma()).toString();
ib_wyslij.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new MyAsyncTask().execute(suma);
}
});
private class MyAsyncTask extends AsyncTask<String, Integer, Double> {
#Override
protected Double doInBackground(String... params) {
// TODO Auto-generated method stub
postData(params[0]);
return null;
}
protected void onPostExecute(Double result) {
Toast.makeText(getApplicationContext(), "command sent",
Toast.LENGTH_LONG).show();
}
public void postData(String valueIWantToSend) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.kuba.ro/exeConn.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("Zam_suma",
valueIWantToSend));
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
}
}
}
Part of my PHP file:
$Zam_suma = $_POST['Zam_suma'];
mysql_query("INSERT INTO Zamowienie(Zam_suma) VALUES($Zam_suma)");
For what do you need the params Integer and Double in your asynctask? If you only need the asynctask to post the string, you can use Void for the other parameters:
private class MyAsyncTask extends AsyncTask<String, Void, Void>
Add the #Override annotation to the onPostExecute() to override the method (see Arjan's answer).
Call e.printStackTrace() in your catch blocks to see when, where and why an error occurs.
Good tutorial
For your PHP file:
Be sure to validate the posted item via PHP, that you are receiving the right value using
is_int is_string, etc.
If your value is supposed to be int, use the following code example.
if (is_int($_POST['example_value']) {
$value = $_POST['example_value'];
}
Also you should not use mysql_query, because it's nearly deprecated. Instead, you should use PDO mysqli.
Related
I have tried to post data into server using Asynctask,but it show only one data it is not accepting multiple data to a file.these are my code.
public class MainActivity extends Activity implements OnClickListener {
private EditText value,value1;
private Button btn;
String string;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
value=(EditText)findViewById(R.id.editText1);
value1=(EditText)findViewById(R.id.editText2);
btn=(Button)findViewById(R.id.button1);
//string=value.getText().toString();
btn.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
public void onClick(View v) {
// TODO Auto-generated method stub
new
MyAsyncTask().execute(value.getText().toString(),value1.getText().toString());
}
private class MyAsyncTask extends AsyncTask<String, Integer, Double>{
#Override
protected Double doInBackground(String... params) {
// TODO Auto-generated method stub
postData(params[0],params[1]);
return null;
}
protected void onPostExecute(Double result){
Toast.makeText(getApplicationContext(), "command sent", Toast.LENGTH_LONG).show();
}
public void postData( String valueIWantToSend,String abc) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.0.104/AndroidUploadImage/receiver.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("myHttpData", valueIWantToSend));
nameValuePairs.add(new BasicNameValuePair("one word",abc));
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
}
}
}
}
private String s;
EditText numDisplay;
Button calculateNow;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
numDisplay= (EditText)findViewById(R.id.editText1);
calculateNow = (Button)findViewById(R.id.button1);
//s=numDisplay.toString();
calculateNow.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
{
new MyAsyncTask().execute(numDisplay.getText().toString());
} }
} );
}
private class MyAsyncTask extends AsyncTask<String, Integer, Double>{
protected Double doInBackground(String... params) {
postData(params[0]);
return null;
}
protected void onPostExecute(Double result){
//pb.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), "command sent", Toast.LENGTH_LONG).show();
}
protected void onProgressUpdate(Integer... progress){
//pb.setProgress(progress[0]);
}
public void postData(String valueIWantToSend) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://1-dot-primecalculation.appspot.com/");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id0", valueIWantToSend));
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
}
}
}
}
**Server Side Code**
private static final long serialVersionUID = 1L;
#Override
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
processRequest(req, resp);
String user = req.getParameter("id0");
//resp.setContentType("text/plain");
PrintWriter writer = resp.getWriter();
writer.write("value" + user);
}
private void processRequest(HttpServletRequest req, HttpServletResponse resp)throws IOException {
// TODO Auto-generated method stub
}
#Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
doPost(req, resp);
}}
I am new to google app engine and android.Made an application in android which takes value from user and post it to servlet.
I used httpClient to post data from android to servlet,hosted locally and sending data from emulator .
I receive null value from servlet side.I googled a lot in this context but not getting solution for the issue.Any help appreciated.Thnx
Here's a simple example:
http://webdeveloperpadawan.blogspot.co.uk/2015/01/google-app-engine-and-android-playing.html
Note the way you define the Google app engine backend service, and then call it in Android code like this:
myApiService.sayHi(name).execute()
Without more specifics I'm not sure what your error is, but be sure your localy hosted servlet is running first. Otherwise you'll never get going. You should be able to test this with a basic web form before moving on to the Android code.
Friends ,i need help to android httppost data to server using Asynctask or Threads
I need to send data to my server when i click post button.But when i click it app need to go to next page and data need to send through as background process.I'm new to Android.I don't know what is exactly use for this kind of task (Threads or Asyanctask).
I tried this code but it will give me exception error
public void startProgress(final String name) {
// Do something long
Runnable runnable = new Runnable() {
#Override
public void run() {
try {
Thread.sleep(500);
send(name);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
new Thread(runnable).start();
}
public void send(String name)
{
// get the message from the message text box
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2:8080/Test");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
String co2 =input_field.getText().toString();
nameValuePairs.add(new BasicNameValuePair("Name", name));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Toast toast = Toast.makeText(getApplicationContext(), "Got it ", Toast.LENGTH_SHORT);
toast.show();
httpclient.execute(httppost);
input_field.setText("");
} catch(Exception e){
Toast toast2 = Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_SHORT);
toast2.show();
}
}
but if i use it this way it works.(text is TextView item in that page)
public void startProgress(final String name) {
// Do something long
Runnable runnable = new Runnable() {
#Override
public void run() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
text.post(new Runnable() {
#Override
public void run() {
send(name);
}
});
}
};
new Thread(runnable).start();
}
What happen in bellow piece of code can you please explain about this also
text.post(new Runnable() {
#Override
public void run() {
send(name);
}
});
please help me to solve this problem.If there is better way to do my need please mentioned it .Because it have very less experience about Android development
You can do this by using AsyncTask like this:
public class HttpPostExanple extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... params)
{
BufferedReader inBuffer = null;
String url = "http://10.0.2.2:8080/Test";
String result = "fail";
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost request = new HttpPost(url);
List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("name", params[0]));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(
postParameters);
request.setEntity(formEntity);
httpClient.execute(request);
result="got it";
} catch(Exception e) {
// Do something about exceptions
result = e.getMessage();
} finally {
if (inBuffer != null) {
try {
inBuffer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
protected void onPostExecute(String page)
{
//textView.setText(page);
Toast toast = Toast.makeText(getApplicationContext(), page, Toast.LENGTH_SHORT);
toast.show();
}
}
And you need to have this in your main method
new HttpPostExample().execute(new String[] {name});
Check this out.
Hope this will help you.
You should implement something like this:
new Thread(new Runnable() {
public void run() {
send(name); // if this method need to access the UI interface you have to use .post method
}
}).start();
About your question: the .post method causes the Runnable to be added to the message queue. The runnable will be run on the user interface thread. [reference]
And this is required because without this method you violate the single thread model: the Android UI toolkit is not thread-safe and must always be manipulated on the UI thread. In your piece of code, the TextView is manipulated on a worker thread, which can cause really weird problems.
As you can see, If the method inside your thread need to access the UI you should use .post method, and this make more laborious the code. So the right solution may be use the AsyncTask that will manage for you the complexity of the threads. You have to put the piace of code that need to access on the UI, in the onPostExecute() method
I suggest you to use robospice or other frameworks as alternative:
Volley
DataDroid
REST Provider
REST Droid
PostMan (rings twice) Lib
Ion
droidQuery
Android Job Queue
Goro
because activity can be recreated before onPostExecute reached. AsyncTask is not good example for networking in Activity.
I'm developing an Android app. I want to post to a server using asynctask. However, I still have an error which indicates that the UI thread is blocked.
I want to parse the XML response and display it in a list view, but I cannot proceed because the UI thread is still blocked.
public class AsynchronousPost extends ListActivity implements OnClickListener {
EditText SearchValue;
Button SearchBtn;
String URL = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_interface);
SearchBtn = (Button) findViewById(R.id.searchbtn);
SearchBtn.setOnClickListener(this);
}
public void onClick(View views) {
new MyAsyncTask().execute();
}
private class MyAsyncTask extends AsyncTask<String, Integer, Document> {
private final String URL = "url";
private final String username = "username";
private final String password = "password";
private EditText SearchValue;
#Override
protected Document doInBackground(String... arg0) {
// TODO Auto-generated method stub
getXmlFromUrl(URL); // getting XML
return null;
}
#Override
protected void onPostExecute() {
//want to parse xml response
//display on listview
}
public String getXmlFromUrl(String url) {
String xml = null;
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
SearchValue = (EditText) findViewById(R.id.search_item);
String Schvalue = SearchValue.getText().toString();
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
5);
nameValuePairs
.add(new BasicNameValuePair("username", username));
nameValuePairs
.add(new BasicNameValuePair("password", password));
nameValuePairs.add(new BasicNameValuePair("searchItem",
Schvalue));
// response stored in response var
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
} catch (ClientProtocolException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
// return XML
return xml;
}
}
}
There are a couple problems that I see. First, you aren't passing anything in execute() but in your class declaration you are telling doInBackground() to expect a String. Secondly, you are telling onPostExecute() to expect a Document but you are returning null from doInBackground() and not taking any parameters in onPostExecute(). Unless I missed something, I don't see how this even compiles
protected Object doInBackground(String... params) {
//this method of AsyncTask is not running on the UI Thread -- here do just non UI taks
return result;
}
#Override
protected void onPostExecute(Object result) {
//I'm not sure but I think this method is running on the UI Thread
//If you have long operations here to do you will block UI Thread
//put the tasks in the doInBackground...
//to fill the elements in the UI elements use
//
runOnUiThread (new Runnable() {
#Override
public void run() {
//here fill your UI elements
}});
}
I have an HttpPost which sends data to a server to be stored on a database. When that data is successfully stored I get a response in my LogCat that says "message has been saved successfully" (this response was defined in my PHP code). I am happy with that, but I am trying to get that same response to be displayed in a Toast. Here is my code:
String myBreadfromr, myBreadtor;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Bundle myBasket = getIntent().getExtras();
myBreadfromr = myBasket.getString("keyfromcellr");
myBreadtor = myBasket.getString("keytocellr");
new SendData().execute("");
}
public class SendData extends AsyncTask<String, Integer, Void> {
protected void onPreExecute(String f) {
// called before doInBackground has started
f = "f";
}
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
// Create a new HTTP client
HttpClient client = new DefaultHttpClient();
// Create a new HTTP Post
HttpPost post = new HttpPost("http://192.xxx.xxx.xxx/androidp2p/process.php");
try {
// Add the data
List<NameValuePair> pairs = new ArrayList<NameValuePair>(3);
pairs.add(new BasicNameValuePair("from", myBreadfromr));
pairs.add(new BasicNameValuePair("to", myBreadtor));
pairs.add(new BasicNameValuePair("message", "What is your location?"));
// Encode Post data into valid URL format
post.setEntity(new UrlEncodedFormEntity(pairs));
// Go back to the first page
Intent back2start = new Intent(RequestLocation.this, StartApp.class);
startActivity(back2start);
// Make the HTTP Post Request
HttpResponse response = client.execute(post);
// Convert the response into a String
final HttpEntity resEntity = response.getEntity();
// Write the response to a log file
if (resEntity != null) {
Log.i("RESPONSE", EntityUtils.toString(resEntity));
}
runOnUiThread(new Runnable(){
public void run() {
Toast.makeText(RequestLocation.this, resEntity.toString(), Toast.LENGTH_LONG).show();
}
});
} catch (UnsupportedEncodingException uee) {
uee.printStackTrace();
} catch (ClientProtocolException cpe) {
cpe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
return null;
}
protected void onProgressUpdate(Integer... progress) {
// called when the background task has made any progress
}
protected void onPostExecute() {
// called after doInBackground has finished
}
}
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
What I see in the Toast instead is: "org.apache.http.conn.BasicManagedEntity#41284b48".
Thanking you in advance for any help in resolving this matter.
Use EntityUtils.toString(resEntity) in the Toast to get the same text.
Also no need to call runOnUiThread, doInBackground must return something, not null, and that something will be available onPostExecute which already is made to run on the UI thread.
AsyncTask