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
}
}
}
}
Related
I'm a newbie in android development. I have to integrate web service in my app but it doesn't work. can someone help me out to resolve it.
Following is the source code
public class Registration extends Activity {
EditText edfnm,edlnm,edmobile,edemail,edpass;
Button b1;
TextView tv1;
private DefaultHttpClient httpclient;
private HttpPost httppost;
private ArrayList<NameValuePair> lst;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
edfnm=(EditText)findViewById(R.id.edfirst);
edlnm=(EditText)findViewById(R.id.edlast);
edmobile=(EditText)findViewById(R.id.edmobile);
edemail=(EditText)findViewById(R.id.edemail);
edpass=(EditText)findViewById(R.id.edpass);
b1=(Button)findViewById(R.id.btnreg);
tv1=(TextView)findViewById(R.id.textView1);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
httpclient=new DefaultHttpClient();
httppost=new HttpPost("http://amwaveswellness.com/protocol_suggestion/webservice/register.php");
lst=new ArrayList<NameValuePair>();
lst.add(new BasicNameValuePair("first_name",edfnm.getText().toString()));
lst.add(new BasicNameValuePair("last_name",edlnm.getText().toString()));
lst.add(new BasicNameValuePair("mobile",edmobile.getText().toString()));
lst.add(new BasicNameValuePair("email",edemail.getText().toString()));
lst.add(new BasicNameValuePair("password",edpass.getText().toString()));
try {
httppost.setEntity(new UrlEncodedFormEntity(lst));
new add_data().execute();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
class add_data extends AsyncTask<String, integer, String>{
String jsonstring;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
try {
HttpResponse httpresponse=httpclient.execute(httppost);
jsonstring=EntityUtils.toString(httpresponse.getEntity());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonstring;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
tv1.setText(result);
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
}
}
});
}
When I run this code it returnsnull responce
Pl tell me what's going on and how to tackle it.
API request sample
This is a good example to achieve it.
https://www.simplifiedcoding.net/android-volley-tutorial-to-get-json-from-server/
go through it.
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.
The code below creates a form whose results are to be posted to server(request to a server)... i tried the same form using html with same form fields it works but here it does not work and redirects to the home page of the website.....
public class MainActivity extends Activity {
Button submit,fpass;
EditText wbpasswd,wblogid;
TextView loginid,password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wblogid = (EditText) findViewById(R.id.wblogid);
wbpasswd = (EditText) findViewById(R.id.wbpasswd);
submit = (Button) findViewById(R.id.submit);
fpass = (Button) findViewById(R.id.fpass);
loginid = (TextView) findViewById(R.id.loginid);
password = (TextView) findViewById(R.id.password);
fpass.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(getBaseContext(), "You have clicked the fpass button",
Toast.LENGTH_SHORT).show();
}
});
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.ebharatgas.com/ebgas/login");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("wblogid", wblogid.getEditableText().toString()));
nameValuePairs.add(new BasicNameValuePair("wbpasswd", wbpasswd.getEditableText().toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
String t = EntityUtils.toString(response.getEntity());
Intent i = new Intent("com.example.ebharatgas.Activity2");
i.putExtra("code", t);
startActivity(i);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}).start();
//Toast.makeText(getBaseContext(), "You have clicked the fpass button",
//Toast.LENGTH_SHORT).show();
}
});
}
}
Also please tell me how can i display the response from the server on my android activity... and i am a beginner of android programming... please help me.... thanks in advance..
give it a try like this:
private class JsonResponse extends AsyncTask {
String response = "";
protected void onPreExecute()
{
}
protected void onPostExecute(String result)
{
if(response.equalsIgnoreCase("Success"))
{
Intent i = new Intent("com.example.ebharatgas.Activity2");
i.putExtra("code", t);
startActivity(i);
}
}
protected String doInBackground(final String... args)
{ List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("wblogid", wblogid.getEditableText().toString()));
nameValuePairs.add(new BasicNameValuePair("wbpasswd", wbpasswd.getEditableText().toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
String t = EntityUtils.toString(response.getEntity());
}
response = "Success";
}
catch(JSONException e)
{
e.printStackTrace();
}
return response;
}
} //Formatting & Code setting required
I am very new to Android hope you anyone could help me.
Whenever I use an OnclickListener to execute an Asynctask, the program will crash. If I execute the Asynctask without using onclicklistener, the testing program works fine.
public class MainActivity extends Activity {
TextView label;
Button start;
MyAsyncTask test;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
label = (TextView)findViewById(R.id.tvIndicator);
start = (Button)findViewById(R.id.btSend);
test = new MyAsyncTask();
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
test.execute();
}
});
}
public class MyAsyncTask extends AsyncTask{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("htt://****.php");//left out the address
#Override
protected Object doInBackground(Object... params) {
// TODO Auto-generated method stub
label.setText("Please Work");
String MyName = "testing";
String response = null;
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("emailAdd", MyName));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
response = httpclient.execute(httppost, responseHandler);
label.setText(response.length());
return response;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
}
you can not update UI element in a Thread different from the UI Thread iteself. You have to use an Handler or use runOnUiThread
For instance
runOnUiThread(new Runnable() {
public void run() {
label.setText("Please Work");
}
});
I'm trying to display process dialog, it is being showed as expected, but when it is being showed, doInBackground() is not being executed, when I press on screen of emulator, then doInBackground() starts executing again.
This is my AsyncTask class:
public class FetchEmployeeAsyncTask extends AsyncTask<String, Void, ArrayList<Employee> > {
private CaptureActivity activity;
//private ProgressDialog progressDialog;
public FetchEmployeeAsyncTask(CaptureActivity nextActivity) {
this.activity = nextActivity;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
/*progressDialog= new ProgressDialog(activity);
progressDialog.setCancelable(true);
progressDialog.setTitle("Fetching Employees!!");
progressDialog.setMessage("Please wait...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setProgress(0);
progressDialog.show();*/
}
#Override
protected ArrayList<Employee> doInBackground(String... url) {
// TODO Auto-generated methoVoidd stub
ArrayList<Employee> employees = null;
for(String employeeUrl : url){
employees = fetch(employeeUrl);
}
return employees;
}
private ArrayList<Employee> fetch(String url) {
// TODO Auto-generated method stub
ArrayList<Employee> employees = null;
String response = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
employees = EmployeeXMLParser.employeeParser(response);
System.out.println("Size in fetch "+employees.size());
//System.out.println("Employee Name :: " + employees.get(0).getFirstName() + " " + employees.get(0).getLastName());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} /*catch (XmlPullParserException e) {
// TODO Auto-generated catch block
System.out.println("Error parsing the response :: " + response);
e.printStackTrace();
}*/
return employees;
}
#Override
public void onPostExecute(ArrayList<Employee> employees){
super.onPostExecute(employees);
System.out.println("in post execxute "+employees.size());
//progressDialog.dismiss();
activity.showEmployees(employees);
}
}
I'm calling AsyncTask in this activity class:
public class CaptureActivity extends Activity {
private String url = "http://192.168.2.223:8680/capture/clientRequest.do?r=employeeList&cid=0";
FetchEmployeeAsyncTask employeeAsyncTask;
private ArrayList<Employee> employees = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("");
employeeAsyncTask = new FetchEmployeeAsyncTask(this);
employeeAsyncTask.execute(new String[] {url});
System.out.println("Status "+employeeAsyncTask.getStatus());
setContentView(R.layout.activity_capture);
}
What are you trying to do here? are you trying to get some values from the database if so check the assignment of the url if you are passing the value correctly.
Also please try explaining your problem in detail and paste some more code.
Try this:
protected void onPreExecute() {
progressDialog = ProgressDialog.show(currentActivity.this, "",
"Message Here", true);
}
protected void onPostExecute(String str) {
dialog.dismiss();
}