How to send http request for php webservices - android

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.

Related

I have to post data into server using asynctask post method

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
}
}
}
}

How to download file from server from button click event in android

I want to create an application using PHP webservices which can download file from server.
This is my Detail class:
public class ImportExportDataDetails extends Activity {
int id;
Button btnback;
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private Button startBtn;
private ProgressDialog mProgressDialog;
TextView txtname,tvfile1,tvfile2,tvdetail;
ImageView imgflag;
Button btnfile1,btnfile2;
String url1,url2,filenm1,filenm2;
private DefaultHttpClient httpclient;
private HttpPost httppost;
private ArrayList<NameValuePair> lst;
public static String[] image;
public static String[] name;
public static String[] file1;
public static String[] file2;
public static String[] fnm1;
public static String[] fnm2;
public static String[] detail;
private JSONArray users =null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_import_export_data_details);
Intent i=getIntent();
id=i.getIntExtra("id", 0);
txtname=(TextView)findViewById(R.id.txtname);
tvfile1=(TextView)findViewById(R.id.tvfile1);
tvfile2=(TextView)findViewById(R.id.tvfile2);
tvdetail=(TextView)findViewById(R.id.tvdetail);
imgflag=(ImageView)findViewById(R.id.imgflag);
btnfile1=(Button)findViewById(R.id.btnfile1);
btnfile2=(Button)findViewById(R.id.btnfile2);
btnback=(Button)findViewById(R.id.btnback);
btnback.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent i=new Intent(getApplicationContext(),ImportExportData.class);
startActivity(i);
}
});
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://kalalunsons.com/webservice/web-import-export-data-details.php?import_export=1");
lst=new ArrayList<NameValuePair>();
lst.add(new BasicNameValuePair("im_ex_data_id", Integer.toString(id)));
try {
httppost.setEntity(new UrlEncodedFormEntity(lst));
new details().execute();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
btnfile1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
startDownload();
}
});
}
private void startDownload() {
String url = url1;
new DownloadFileAsync().execute(url);
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Downloading file..");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
class DownloadFileAsync extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected String doInBackground(String... aurl) {
int count;
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
// Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/file.xlsx");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC",progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
class details 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);
JSONObject JsonObject=null;
try {
JsonObject =new JSONObject(result);
JSONObject jobj=JsonObject.getJSONObject("0");
users=jobj.getJSONArray("import_export");
name=new String[users.length()];
image=new String[users.length()];
detail=new String[users.length()];
file1=new String[users.length()];
file2=new String[users.length()];
fnm1=new String[users.length()];
fnm2=new String[users.length()];
for(int i=0;i<users.length();i++){
JSONObject jo=users.getJSONObject(i);
name[i]=jo.getString("name");
image[i]=jo.getString("image");
detail[i]=jo.getString("details");
file1[i]=jo.getString("file");
file2[i]=jo.getString("file2");
fnm1[i]=jo.getString("file_name");
fnm2[i]=jo.getString("file_name");
txtname.setText(name[i]);
Picasso.with(getApplicationContext()).load(image[i]+"?import_export=1").into(imgflag);
tvdetail.setText(Html.fromHtml(detail[i]));
tvfile1.setText(fnm1[i]);
tvfile2.setText(fnm2[i]);
url1=file1[i];
url2=file2[i];
filenm1=tvfile1.getText().toString();
filenm1=filenm1.toLowerCase()+".xlsx";
}
//Toast.makeText(getApplicationContext(), url1, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
In that case the logcat doesn't display any error.when i run this code it start progress of downloading,when progress finished i check my sdcard folder but it not display any file.the file was downloaded successfully but it displays as binary format,what can i changes in my code.and how can i display it in the sdcard.
you can use some library for network calls:-
retrofit-
http://www.androidhive.info/2016/05/android-working-with-retrofit-http-library/
also background and UI threads are separate threads. In UI thread, you can update your views and UI like toast messages and load an image.
here is a great article to learn about asynctask, read this first --
https://androidresearch.wordpress.com/2012/03/17/understanding-asynctask-once-and-forever/
Issue: you are showing Toast in doInBackground() which run in separate thread. Remove Toast message from doInBackground() method
If you wanna show some info,use logs instead of Toast

how to use progress with Asynctask get method?

I want to use progress bar... but As I searched, progress bar can not use with Asynctask.get.But I have to use .get and progress in Asynctask.
I made very simple source.
How can I changed to show progress bar in main thread??
I want to use both get method and ui progress.
public void onCreate(Bundle savedInstanceState) {
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
AAA asyncTask = new AAA();
try {
((AAA) asyncTask).execute(null, null, null,null).get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public class AAA extends AsyncTask<Object, String, Object> {
private ProgressDialog progDailog = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
progDailog = new ProgressDialog(ViewTestActivity.this);
progDailog.setMessage("Loading...");
progDailog.setIndeterminate(false);
progDailog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progDailog.setCancelable(true);
progDailog.show();
}
#Override
protected Object doInBackground(Object... params) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return params;
}
#Override
protected void onPostExecute(Object result) {
progDailog.dismiss();
}
}
Please help me.
Thanks!!
Do it before calling AsyncTask
private ProgressDialog progDailog = null;
public void onCreate(Bundle savedInstanceState) {
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
AAA asyncTask = new AAA();
try {
progDailog = new ProgressDialog(ViewTestActivity.this);
progDailog.setMessage("Loading...");
progDailog.setIndeterminate(false);
progDailog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progDailog.setCancelable(true);
progDailog.show();
((AAA) asyncTask).execute(null, null, null,null);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public class AAA extends AsyncTask<Object, String, Object> {
#Override
protected Object doInBackground(Object... params) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return params;
}
#Override
protected void onPostExecute(Object result) {
progDailog.dismiss();
}
}
I don't know if there's a standard answer, but I've just done something very similar by setting up listener on the main thread, and sending progress messages to the listener from the async task - actually in my case it was loading asynchronously from a database. Works fine for me.
Try with this :
private ProgressDialog progDailog;
public void onCreate(Bundle savedInstanceState) {
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
progDailog = new ProgressDialog(ViewTestActivity.this);
progDailog.setMessage("Loading...");
progDailog.setIndeterminate(false);
progDailog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progDailog.setCancelable(true);
progDailog.show();
AAA asyncTask = new AAA(progDialog);
try {
((AAA) asyncTask).execute(null, null, null,null).get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public class AAA extends AsyncTask<Object, String, Object> {
private ProgressDialog progressDialog;
public AAA (ProgressDialog progressDialog) {
this.progressDialog = progressDialog;
}
#Override
protected Object doInBackground(Object... params) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return params;
}
#Override
protected void onPostExecute(Object result) {
progressDialog.dismiss();
}
}
you should update your progress bar percentage in onProgressUpdate
See this example AsyncTask with progress bar

io.socket.SocketIOException: Error while handshaking

I Am developing an Android application using Socket.Io.When i use my local ip address (192.168.1.22:4000) i got respose from server.But when i use with domain Name ("http://mydomainname.com:80) I got io.socket.SocketIOException: Error while handshaking Exception how can i handle this.Please check below code>thanks in advance.
JSONObject js = new JSONObject();
js.put("key",value);
js.put("key",value);
socket = new SocketIO();
socket = new SocketIO("http://mydomain.com:80");
socket.addHeader("id", 20);
socket.connect(new IOCallback()
{
#Override
public void onMessage(JSONObject json, IOAcknowledge ack)
{
// TODO Auto-generated method stub
System.out.println(".....onMessage.......");
}
#Override
public void onMessage(String data, IOAcknowledge ack)
{
// TODO Auto-generated method stub
System.out.println(".....onMessage... STR....");
}
#Override
public void onError(SocketIOException socketIOException)
{
// TODO Auto-generated method stub
}
#Override
public void onDisconnect()
{
// TODO Auto-generated method stub
}
#Override
public void onConnect()
{
// TODO Auto-generated method stub
System.out.println("....connected ....");
}
#Override
public void on(String event, IOAcknowledge ack, Object... args)
{
// TODO Auto-generated method stub
Object[] arguments = args;
JSONObject jsb = (JSONObject) arguments[0];
} catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
},js,"event name");
} catch (MalformedURLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}

when process dialog is being displayed, doInBackground() is not being executed

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

Categories

Resources