Get data from website using android
by mariganesh[ Edit ] 2013-07-05 17:43:21
Get data from website using android
If you want to get the data from website by asynchrnous task(Coding running in Backend) using this Android class
Asynchrnous task Class
use this coding for data fetching operation from website in Backend
class getHTML extends AsyncTask<String, String , String> {
private ProgressDialog mProgressDialog;
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
public getHTML(Context context) // Display the Progress bar
{
mProgressDialog = new ProgressDialog(context);
mProgressDialog.setMessage("Loading...");
mProgressDialog.setCancelable(false);
}
@Override
protected void onPostExecute(String result) {
displaydata(result);// After fethcing the data from website, displaydata function should be calling
mProgressDialog.dismiss();
}
@Override
protected void onPreExecute() {
mProgressDialog.show();
}
@Override
protected String doInBackground(String... params) {
String resultstring1 = null;
try {
resultstring1 = get_data(params[0],params[1],params[2]);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//Toast.makeText(getApplicationContext(), "Home Page2", Toast.LENGTH_LONG).show();
return resultstring1;
}
}
Get Data function
This function can be used to get the data from website and return data to "onPostExecute" function
public String get_data(String uid , String mailid , String calcid) throws IOException{
InputStream is = null;
String outp="";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("Give your URl"); //Give your URl
try {
//Create a NameValuePair
List<NameValuePair> namevaluePairs = new ArrayList<NameValuePair>(1);
namevaluePairs.add(new BasicNameValuePair("custom",custm));//pass the parameter value and Name
//Encode Value in URL and Execute the Client
httppost.setEntity(new UrlEncodedFormEntity(namevaluePairs));
HttpResponse response=httpclient.execute(httppost);
response = httpclient.execute(httppost);
outp = request(response);
} catch (ClientProtocolException e) {
outp = "Error1";
e.printStackTrace();
} catch (IOException e) {
outp = "Check your Network Connection";
}
} finally {
if (is != null) {
is.close();
}
}
return outp;
}
//Get The response from website
public String request(HttpResponse response){
String result = "";
try{
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in,'iso-8859-1'),8 );
StringBuilder str = new StringBuilder();
str.append(reader.readLine() + "n");
String line="0";
while ((line = reader.readLine()) != null) {
str.append(line + "n");
}
in.close();
String resulttemp = str.toString();
result = resulttemp;
}catch(Exception ex){
result = "Error3";
}
return result;//return the result to "onPostExecute" function
}
Display Data
Here display the data using by this function.
public void insertdata(String result) {
//disply the data
}