The idea is duplicate on android this web
http://www.telekino.com.ar/
In the site there is a form to check if your lottery ticket won
I am confused on how do it. I tried at this way
my layout has three EditText for each one of the form data to be sent (emision,cupon,algoritmo), to be similar to the web, and a button to send the values.
This is my class
public class Control extends Activity {
private EditText Numerocarton;
private EditText Algoritmo;
private EditText Emision;
public static String emision, cupon, algo;
public TextView resultadocarton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.control);
Emision = (EditText)findViewById(R.id.emsion);
Numerocarton = (EditText)findViewById(R.id.numerocarton);
Algoritmo = (EditText)findViewById(R.id.algoritmo);
emision= Emision.getText().toString();
cupon= Numerocarton.getText().toString();
algo= Algoritmo.getText().toString();
Button resultados= (Button) findViewById(R.id.controlcartonbut);
resultados.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Title().execute();
}
});
resultadocarton =(TextView)findViewById(R.id.resultadocarton);
}
// Title AsyncTask
private class Title extends AsyncTask<Void, Void, Void> {
String responseString;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
HttpClient client=new DefaultHttpClient();
HttpPost post=new HttpPost("http://www.telekino.com.ar/");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
nameValuePairs.add(new BasicNameValuePair("emision", emision));
nameValuePairs.add(new BasicNameValuePair("cupon", cupon));
nameValuePairs.add(new BasicNameValuePair("algo", algo));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response=client.execute(post);
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity, "UTF-8");
resultadocarton.setText(responseString);
}
catch(Exception e){
Log.e("exvcx", "error getting data" + e.toString());
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
resultadocarton.setText(responseString);
}
}
}
I dont receive results,and mean there is no change on the EditText. Suggestions? maybe other way to create the clon
You need to know the complete endpoint of the service which is getting called after pressing the controla button. I checked the url given by you. It uses the ajax to contact the webservice and get the data.
Hello i am not sure but may be there is a issue in this line
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Should be like...
post.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));
Please check it and reply if you are still getting this issue.
also check all the parameters KeyName
Thanks!
Related
I am trying to POST data using an http request method from an Android application to a Wamp server.
When I run the application a success message is shown on the Android app, but there is no data inserted in the table of the Wamp server. There is no error shown on logcat. What am I doing wrong?
public class MainActivity extends Activity {
private EditText editTextName;
private EditText editTextAdd;#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextName = (EditText) findViewById(R.id.editTextName);
editTextAdd = (EditText) findViewById(R.id.editTextAddress);
}
public void insert(View view) {
String name = editTextName.getText().toString();
String add = editTextAdd.getText().toString();
insertToDatabase(name, add);
}
private void insertToDatabase(String name, String add) {
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String paramUsername = params[0];
String paramAddress = params[1];
String name = editTextName.getText().toString();
String add = editTextAdd.getText().toString();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name", name));
nameValuePairs.add(new BasicNameValuePair("address", add));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://ip address of my system/Employee3/create_product.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return "success";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
TextView textViewResult = (TextView) findViewById(R.id.textViewResult);
textViewResult.setText("Inserted");
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(name, add);}
}
For the Http debugging, I suggest you firstly use some tools to test the interface, such as curl or postMan. Make sure the post/get method work correct in these tools, then test the interface in Android
I am making a register screen for my project. After register data is sent to web database I want the app also update local sqlite database so that the next time user opens the app, he/she doesn't need to do the same operations if the register is successfull. My app is updating the web database with no problem but when I try to do sqlite update with a second asynctask it doesn't update sqlite, what am I missing? :(
Here is my code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
final EditText vmail=(EditText) findViewById(R.id.editText1);
final EditText vpassword=(EditText) findViewById(R.id.editText2);
final EditText vnickname=(EditText) findViewById(R.id.editText3);
Button button2=(Button) findViewById(R.id.button1);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mail=vmail.getText().toString();
password=vpassword.getText().toString();
mynickname=vnickname.getText().toString();
new AsyncTaskClass().execute();
}
});
}
class AsyncTaskClass extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(Void... params) {
String reverseString =null;
try
{
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("mail",mail));
nameValuePairs.add(new BasicNameValuePair("password",password));
nameValuePairs.add(new BasicNameValuePair("mynickname",mynickname));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("wwwmysite.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = httpclient.execute(httppost, responseHandler);
reverseString = response;
} catch (ClientProtocolException e) {
Log.e("log_tag", "Error converting result " + e.toString());
} catch (IOException e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
return reverseString;
}
protected void onPostExecute(String reverseString) {
if (reverseString.contains("success")){
new AsyncTaskClass2().execute();
}else{
Toast.makeText(getApplicationContext(), reverseString, Toast.LENGTH_LONG).show();
}
}
}
class AsyncTaskClass2 extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(Void... params) {
String reverseString =null;
try
{
KayitEkle(Array.get(nameValuePairs, 0).toString(),Array.get(nameValuePairs, 1).toString(),Array.get(nameValuePairs, 2).toString());
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
return reverseString;
}
protected void onPostExecute(String reverseString) {
startActivity(new Intent(registergame.this, (mygamescreen.class)));
}
}
private void KayitEkle(String nick, String mail, String password){
SQLiteDatabase db = users.getWritableDatabase();
ContentValues veriler = new ContentValues();
veriler.put("nick", nick);
veriler.put("mail",mail);
veriler.put("password",password);
db.insertOrThrow("ogrenciisim", null, veriler);
}
}
Put a debugger to see if it is actually calling AsyncTaskClass2 doInBackground() method. If it does, then check the value returned by method insertOrThrow(). If return value is -1 then you need to check for that. This link will give you some insight
You declared your nameValuePairs-variable only in your doInBackground-Method of your 1st AsyncTask:
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
You could simply solve it, if you use your class-attribute nameValuePairs:
nameValuePairs = new ArrayList<NameValuePair>();
But as a general aspect, I do not see any cause why you should use a 2nd AsyncTask. Why don't you call the method
KayitEkle(Array.get(nameValuePairs, 0).toString(),Array.get(nameValuePairs, 1).toString(),Array.get(nameValuePairs, 2).toString());
in the doInBackground-Method of your 1st AsyncTask?
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
}});
}
Here I am trying to retrieve the response from the server and display it, but I am failed to do so, the response text does not appear in my text view, insetead the default value of the string does, may I ask how can I achieve my goal. And why my code cannot finish the task.
Here is my android program:
public class Chico extends Activity {
GrabURL grab;
TextView mRespond;
String line;
#Override
public void onCreate(Bundle savedInstanceState) {
//create the activity
super.onCreate(savedInstanceState);
//set up the layout
setContentView(R.layout.activity_chico);
mRespond = (TextView) findViewById(R.id.Respond);
mRespond.setVisibility(View.GONE);
grab = new GrabURL();
line = "line";
//set up the button for check in
Button btnin = (Button) findViewById(R.id.inbutton);
btnin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//set the values
grab.onPreExecute("TechID", Build.SERIAL);
grab.onPreExecute("Type", "Checkin");
//set the destination and send the request
grab.execute(new String[]{"http://192.168.1.150/Me/testing.php"});
//close the activity
mRespond.setVisibility(View.VISIBLE);
mRespond.setText(line);
//finish();
}
});
}
private class GrabURL extends AsyncTask<String, Void, Void>{
//ArrayList object for storing the string pairs
ArrayList<NameValuePair> nameValuePairs;
public GrabURL() {
//constructor of the class
nameValuePairs = new ArrayList<NameValuePair>();
}
protected void onPreExecute(String key, String value) {
//store the pair of values into the ArrayList
nameValuePairs.add(new BasicNameValuePair(key,value));
}
#Override
protected Void doInBackground(String... urls) {
// TODO Auto-generated method stub
//Operation being executed in another thread
try{
//set up the type of HTTPClient
HttpClient client = new DefaultHttpClient();
//set up the location of the server
HttpPost post = new HttpPost(urls[0]);
//translate form of pairs to UrlEncodedFormEntity
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8);
//set up the entity being sent by post method
post.setEntity(ent);
//execute the url and post the values
HttpResponse responsePOST = client.execute(post);
HttpEntity resEntity = responsePOST.getEntity();
line = EntityUtils.toString(resEntity);
} catch (Exception e) {
//catch the exception
line = "Can't connect to server";
}
return null;
}
protected void onPostExecute(Void unused) {
Toast.makeText(getApplicationContext(), "Value updated", Toast.LENGTH_SHORT).show();
}
}
}
And here is the php file, it just prints a line:
<?php
print "testing";
?>
Move this code to your AsyncTask's onPostExecute():
...
mRespond.setVisibility(View.VISIBLE);
mRespond.setText(line);
public static class TestTask extends AsyncTask<Void, Integer, Integer> {
private String stacktrace;
public TestTask (String stacktrace){
this.stacktrace = stacktrace;
}
#Override
protected Integer doInBackground(Void... params) {
try {
Log.i("async", "doInBackground 1"); //this gets logged
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://xx.xx:8080/android/service.php");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("action", "logexception"));
nameValuePairs.add(new BasicNameValuePair("stacktrace", stacktrace));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
Log.i("async", "doInBackground 2"); //this gets logged
return 1;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
protected void onPreExecute(){
Log.i("async", "onPreExecute"); //this gets logged
}
#Override
protected void onPostExecute(Integer result) {
Log.i("async", "onPostExecute"); //this doenst get logged!
}
}
I've been checking out the other SO threads regarding this, but according to them, my code looks correct as far as i can tell. So why do i never reach Log.i("async", "onPostExecute");? Thanks
Did you create your AsyncTask on UI Thread?
Others seems good. Generics and annotations are fine.
So probably problem is that your doInBackground method never returns because onPostExecute is automatic called when doInBackground something will return.
You have to call the super in onPostExecute()
So you code should be like this:
#Override
public void onPostExecute(Integer result) {
super.onPostExecute(result);
Log.i("async", "onPostExecute");
}
And this should work