Android Asynctask post to server error - android

Am new to android and developing an android app that posts a search item (which is supplied by user into an EditText) to the server when a button is clicked,the item is posted to the server.Am using Asynctask class.I have error with the findViewById(it is undefined).My problem is where to place the onclick method and referncing of the views.Here is the code
public class Server_Post extends AsyncTask<String, Void, String> {
private static final int REGISTRATION_TIMEOUT = 3 * 1000;
private static final int WAIT_TIMEOUT = 30 * 1000;
private final HttpClient httpclient = new DefaultHttpClient();
final HttpParams params = httpclient.getParams();
HttpResponse response;
Button Submit = (Button) findViewById(R.id.submitButton);
EditText textvalue = (EditText)findViewById(R.id.searcheditText);
//Onclick Listener
Submit.setOnClickListener(onClickListener)
private OnClickListener onClickListener = new OnClickListener() {
#Override
public void onClick(final View v) {
switch(v.getId()){
case R.id.submitButton:
break;
}
};
protected void onPreExecute() {
//any code
}
#Override
protected String doInBackground(String... arg0) {
String URL = "url";
String username = "abc";
String password = "xyz";
try {
HttpConnectionParams.setConnectionTimeout(params, REGISTRATION_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, WAIT_TIMEOUT);
ConnManagerParams.setTimeout(params, WAIT_TIMEOUT);
HttpPost httpPost = new HttpPost(URL);
//Any other parameters you would like to set
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username",username));
nameValuePairs.add(new BasicNameValuePair("password",password));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Response from the Http Request
response = httpclient.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
//Check the Http Request for success
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
}
else{
//Closes the connection.
Log.w("HTTP1:",statusLine.getReasonPhrase());
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}catch (Exception e) {
}
return null;
}
protected void onCancelled() {
}
protected void onPostExecute(String content) {
}
private void connecttopostdata() {
Server_Post task = new Server_Post();
task.execute(textvalue.getText().toString());
}
}
the response is in xml and i want to also dispaly the response on listviews.
Thanks in advance.

You need a context of an activity class to get button from findviewbyid . Make a constructor and find your views from there. Like..
// give context from where you are calling your AsyncTask
public Server_Post (Context context)
{
Button Submit = (Button) context.findViewById(R.id.submitButton);
EditText textvalue = (EditText)context.findViewById(R.id.searcheditText);
}

Related

httppost method of android doesnt work with namevalue pairs

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

Connecting and getting data through web API in android

Can anybody please help me with this one. I am trying to get information in a server through web API, I believe, in my code below that I can already connect to the server (because no error appear). But when I am trying to display information that that I get, it display null value. I'm not sure where a forgot something or if my way of parsing it is right.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonGetData = (Button) findViewById(R.id.buttonGetData);
editTextSearchString = (EditText) findViewById(R.id.editTextSearchString);
textViewFirstName = (TextView) findViewById(R.id.textViewFirstName);
textViewLastName = (TextView) findViewById(R.id.textViewLastName);
display = (TextView) findViewById(R.id.display);
spn_Display = (Spinner)findViewById(R.id.spn_Display);
//Setup the Button's OnClickListener
buttonGetData.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//Get the data
in = null;
DoPOST mDoPOST = new DoPOST(MainActivity.this, editTextSearchString.getText().toString());
Toast.makeText(getApplicationContext(), editTextSearchString.getText().toString(), 6).show();
mDoPOST.execute("");
buttonGetData.setEnabled(false);
}
});
}
public class DoPOST extends AsyncTask<String, Void, Boolean>
{
Context mContext = null;
String strNameToSearch = "";
//Result data
String strFirstName;
String strLastName;
int intAge;
int intPoints;
Exception exception = null;
DoPOST(Context context, String nameToSearch){
mContext = context;
strNameToSearch = nameToSearch;
}
#Override
protected Boolean doInBackground(String... arg0) {
try{
//Setup the parameters
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("Username", "admin"));
nameValuePairs.add(new BasicNameValuePair("Password", "admin123"));
//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://examplesvr4.sample.com:1217/api/subbrands");
HttpGet httpget = new HttpGet("http://examplesvr4.sample.com:1217/api/subbrands");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity);
// Create a JSON object from the request response
JSONObject jsonObject = new JSONObject(result);
//Retrieve the data from the JSON object
strFirstName = jsonObject.getString("SubBrandId");
strLastName = jsonObject.getString("SubBrandName");
}catch (Exception e){
Log.e("ClientServerDemo", "Error:", e);
exception = e;
}
return true;
}
#Override
protected void onPostExecute(Boolean valid){
//Update the UI
textViewFirstName.setText("First Name: " + strFirstName);
textViewLastName.setText("Last Name: " + strLastName);
buttonGetData.setEnabled(true);
if(exception != null){
Toast.makeText(mContext, exception.getMessage(), Toast.LENGTH_LONG).show();
}
}
}

HTTP request that throws a null exception

I have an activity that create a new instance of connection. like this:
public class myActivity extends Activity {
TextView tv;
ProgressDialog dialog = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.daily_news);
gestureDetector = new GestureDetector(new SwipeGestureDetector());
tv = (TextView) findViewById(R.id.tx);
dialog = ProgressDialog.show(myActivity.this, "","Validating user...", true);
connection con = new connection(dialog);
final String str =con.connect_to_db("http://10.0.2.2:8000/daily/my.php");
runOnUiThread(new Runnable() {
public void run() {
tv.setText(str);
dialog.dismiss();
}
});
}
}
in connection class i have an HttpResponse that returns null. like this:
public class connection {
private HttpPost httppost;
private HttpClient httpclient;
private HttpResponse response;
private ProgressDialog dialog = null;
private String result;
public connection(ProgressDialog di){
dialog = di;
}
public String connect_to_db(String url){
try{
httpclient=new DefaultHttpClient();
httppost= new HttpPost(url);
response=httpclient.execute(httppost);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
result = httpclient.execute(httppost, responseHandler);
}catch(Exception e){
dialog.dismiss();
System.out.println("Exception : " + e.getMessage());
}
return result;
}
}
why the value of "result" in connection class is null?
This line:
final String str =con.connect_to_db("http://10.0.2.2:8000/daily/my.php");
Should not be written in the onCreate, but rather in a separate thread => NetworkOnMainThreadException
For your NullPointer, please tell us if you have the Internet permission in Manifest and if response is null or not.
May be because you are doing network operation in onCreate Method. It will not create any problem if you are using android2.2, but if it is HoneyComb then chances are that it is causing some exception and finally you are getting null value. Move the code to onResume() method.
For Simplicity use
HttpResponse response = httpclient.execute(httppost);
and
String valueString = EntityUtils.toString(response.getEntity());
int statusCode = response.getStatusLine().getStatusCode();
print these values and see the out put.

Fail to display server's respond

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);

android http post asynctask

Please can anyone tell me how to make an http post to work in the background with AsyncTask and how to pass the parameters to the AsyncTask? All the examples that I found were not clear enough for me and they were about downloading a file.
I'm running this code in my main activity and my problem is when the code sends the info to the server the app slows down as if it is frozen for 2 to 3 sec's then it continues to work fine until the next send. This http post sends four variables to the server (book, libadd, and time) the fourth is fixed (name)
Thanks in advance
public void SticketFunction(double book, double libadd, long time){
Log.v("log_tag", "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SticketFunction()");
//HttpClient
HttpClient nnSticket = new DefaultHttpClient();
//Response handler
ResponseHandler<String> res = new BasicResponseHandler();
HttpPost postMethod = new HttpPost("http://www.books-something.com");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
nameValuePairs.add(new BasicNameValuePair("book", book+""));
nameValuePairs.add(new BasicNameValuePair("libAss", libass+""));
nameValuePairs.add(new BasicNameValuePair("Time", time+""));
nameValuePairs.add(new BasicNameValuePair("name", "jack"));
//Encode and set entity
postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
//Execute
//manSticket.execute(postMethod);
String response =Sticket.execute(postMethod, res).replaceAll("<(.|\n)*?>","");
if (response.equals("Done")){
//Log.v("log_tag", "!!!!!!!!!!!!!!!!!! SticketFunction got a DONE!");
}
else Log.v("log_tag", "!!!!!!!?????????? SticketFunction Bad or no response: " + response);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
//Log.v("log_tag", "???????????????????? SticketFunction Client Exception");
} catch (IOException e) {
// TODO Auto-generated catch block
//Log.v("log_tag", "???????????????????? IO Exception");
}
}
}
At first,
You put a class like following:
public class AsyncHttpPost extends AsyncTask<String, String, String> {
interface Listener {
void onResult(String result);
}
private Listener mListener;
private HashMap<String, String> mData = null;// post data
/**
* constructor
*/
public AsyncHttpPost(HashMap<String, String> data) {
mData = data;
}
public void setListener(Listener listener) {
mListener = listener;
}
/**
* background
*/
#Override
protected String doInBackground(String... params) {
byte[] result = null;
String str = "";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(params[0]);// in this case, params[0] is URL
try {
// set up post data
ArrayList<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
Iterator<String> it = mData.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
nameValuePair.add(new BasicNameValuePair(key, mData.get(key)));
}
post.setEntity(new UrlEncodedFormEntity(nameValuePair, "UTF-8"));
HttpResponse response = client.execute(post);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpURLConnection.HTTP_OK){
result = EntityUtils.toByteArray(response.getEntity());
str = new String(result, "UTF-8");
}
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
catch (Exception e) {
}
return str;
}
/**
* on getting result
*/
#Override
protected void onPostExecute(String result) {
// something...
if (mListener != null) {
mListener.onResult(result)
}
}
}
Now.
You just write some lines like following:
HashMap<String, String> data = new HashMap<String, String>();
data.put("key1", "value1");
data.put("key2", "value2");
AsyncHttpPost asyncHttpPost = new AsyncHttpPost(data);
asyncHttpPost.setListener(new AsyncHttpPost.Listener(){
#Override
public void onResult(String result) {
// do something, using return value from network
}
});
asyncHttpPost.execute("http://example.com");
First i would not recommend do a Http request in a AsyncTask, you better try a Service instead. Going back to the issue on how to pass parameter into an AsyncTask when you declared it you can defined each Object class of the AsyncTask like this.
public AsyncTask <Params,Progress,Result> {
}
so in your task you should go like this
public MyTask extends<String,Void,Void>{
public Void doInBackground(String... params){//those Params are String because it's declared like that
}
}
To use it, it's quite simple
new MyTask().execute("param1","param2","param3")

Categories

Resources