I am a newbie to android development so please be patient with me.
I am trying to post user id and password to a PHP page and return data (page working fine, tested and returns Json data).
I followed online guides and had similar problem to:
How to send data to a website using httpPost, app crashes
So I followed what was said in the following Answer within the above post
https://stackoverflow.com/a/18588948/3415061
No more Errors , but now how do I control what happens after data returned and if valid how do I go to the next screen and display it?
The following function executes the request but how I do I get the response to the screen if valid or not.
#Override
protected Boolean doInBackground(Void... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.blag.com/blag.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("acc", "blag"));
nameValuePairs.add(new BasicNameValuePair("usr", "blag"));
nameValuePairs.add(new BasicNameValuePair("pass", "blag"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
return true;
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false ;
}
Or am I suppose to access the response in here, but I tried to launch another screen from here but I got errors.
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if(result){
//successful request
}else{
//error in request response
}
// msgTextField.setText(""); // clear text box
}
Am I taking the correct approach to doing this?
Thanks in advance!!!
new code:
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(result=="HEllO"){
//successful request
Intent dashboard = new Intent(getApplicationContext(), MainOrder.class);
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
//userFunction.logoutUser(getActivity().getApplicationContext());
}else{
//error in request response
}
// msgTextField.setText(""); // clear text box
}
error on GetApplicationContext:
The method getApplicationContext() is undefined for the type NetRequestAsync
and error on line Command StartActivity
The method startActivity(Intent) is undefined for the type NetRequestAsync
If this code is inside an Activity of name, let's say MyCoolActivity, then you can access those methods with MyCoolActivity.this.getApplicationContext() and MyCoolActivity.this.startIntent()
Related
i try to send information from android app to server to save in data base my code runs correctly but no data saved in database and i didn't get any response. i don't know where is the mistake in my code
private class postData extends AsyncTask<String, Void, String> {
// private final ProgressDialog dialog = ProgressDialog.show(getActivity(), "",
// "Saving data to server. Please wait...", true);
#Override
protected String doInBackground(String... params) {
// perform long running operation operation
// SharedPreferences settings = context.getSharedPreferences(PREFS_FILE, 0);
//String server = settings.getString("server", "");
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://phone.com/request_job");
String json = "";
String responseStr="";
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("ticket", "welcome"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
try {
httpclient.execute(httppost);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
// Execute HTTP Post Request
// ResponseHandler<String> responseHandler=new BasicResponseHandler();
//String responseBody = httpclient.execute(httppost, responseHandler);
// if (Boolean.parseBoolean(responseBody)) {
// dialog.cancel();
// }
HttpResponse response = httpclient.execute(httppost);
responseStr = EntityUtils.toString(response.getEntity());
} catch (IOException e) {
// TODO Auto-generated catch block
Log.i("HTTP Failed", e.toString());
}
return responseStr;
}
protected void onPostExecute(String responseStr) {
super.onPostExecute(responseStr);
Toast.makeText(getActivity(),responseStr,Toast.LENGTH_LONG).show();
if(responseStr.equals("true")){
// Update your Button here
Toast.makeText(getActivity(),"donefinally",Toast.LENGTH_LONG).show();
}
}
}
my code in server
public function check_user(Request $request){
$ticket = new ticket;// this line responsible to set data in database
$ticket->ticket = $request->ticket;
return response()->json(['data','true']);
}
}
In your server, do
$ticket = new ticket;// this line responsible to set data in database
$ticket->ticket = $request->ticket;
$ticket->save(); //<-- this line will save
Or in one go
$ticket = Ticket::create([
'ticket' => $request->ticket
]);
...
Now, make sure you call your ticket class properly. Not sure whether it's capital T (Ticket) or lowercase (ticket).
Edit
Since it's not working, you need to debug it step by step to see where the bottleneck is. First, in your function, simply do
return response()->json($request->ticket);
//This will prove that the request makes it to the server
Once you are sure you request makes it to the server, try to manually save something like
Ticket::create([
'ticket' => 'random string'
]);
You can call this function directly from your browser to test if it works. If nothing is saved in the db, make sure you have a $fillable array in your model and that you can connect properly to the db.
I develop an android code for transmit and received between android apps and PHP. The received part which is based on JSON, is properly working. I have tested by set variable manually in PHP code. However, when I have posted the variable from android to php, it cannot receive it. Anyone can tell me the problem ?
#Override
protected String doInBackground(Void... params) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", <Your username here>));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(<Your URL to php file>);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
HttpResponse response = httpclient.execute(httppost); // Execute Post to URL
String st = EntityUtils.toString(response.getEntity()); // This is the result from php web
Log.d(TK_Configuration.TAG, "In the try Loop" + st); // Still executing
finalResult = st; // You should register a variable for finalResult;
} catch (Exception e) {
Log.d(TK_Configuration.TAG, "Connection error : " + e.toString());
}
return "OK";
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
// After that, you will have final result and process to do with it here
// Below is my simple code, please change it
if(finalResult.equals("1")){
Toast.makeText(context, context.getResources().getString(R.string.upload_bike_success), Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(context, context.getResources().getString(R.string.upload_bike_fail), Toast.LENGTH_SHORT).show();
}
// End
}
Please try this, and one more point, you should use Gson library to decode JSON quickly to Java Object after you got JSON string from server.
Note: Replace TK_Configuration.TAG << by your TAG.
you have commented this line it means you are not passing values from Android
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
remove comment from this line.
One more thing, you are passing username but from php you are trying to fetch value as $user = $_POST['name'];, both name must be same.
How to send a simple http command without opening the browser??
public void addListenerOnButton() {
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent browserIntent =
new Intent(Intent.ACTION_VIEW, Uri.parse("http://192.168.1.95:8080/json.htm?type=command¶m=switchlight&idx=2&switchcmd=Off&level=0"));
startActivity(browserIntent);
}
});
I think, I know what you want to do. A simple example here, could be helpful.
HTTPClient is what you are looking for. Make sure to use it in a background thread, e.g. in an AsyncTask.
A tutorial like this will get you started: http://hmkcode.com/android-internet-connection-using-http-get-httpclient/
The same question Make an HTTP request with android
Simply, here is the code ( http://www.androidhive.info/2011/10/android-making-http-requests/ )
// Creating HTTP client
HttpClient httpClient = new DefaultHttpClient();
// Creating HTTP Post
HttpPost httpPost = new HttpPost(
"http://www.example.com/login");
// Building post parameters
// key and value pair
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
nameValuePair.add(new BasicNameValuePair("email", "user#gmail.com"));
nameValuePair.add(new BasicNameValuePair("message",
"Hi, trying Android HTTP post!"));
// Url Encoding the POST parameters
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
} catch (UnsupportedEncodingException e) {
// writing error to Log
e.printStackTrace();
}
// Making HTTP Request
try {
HttpResponse response = httpClient.execute(httpPost);
// writing response to log
Log.d("Http Response:", response.toString());
} catch (ClientProtocolException e) {
// writing exception to log
e.printStackTrace();
} catch (IOException e) {
// writing exception to log
e.printStackTrace();
}
For some reason I can not get my async task to pass along the post params I set. Any help is appreciated.
Here is my onClick which calls the thread. Please note that customerInfo is not null, and each index has a value.
EDITED: moved client and post declaration into doInBackground and took out extra, unneeded thread.
EDITED2: Apparently when hitting a subdirectory on your web server, and you declare your url like
http://IP/subDirectory
without the trailing "/" apache doesn't pass the parameter to your index.php.
#Override
public void onClick(View v) {
new RegisterPost(progress).execute();
}
Here is my doInBackground
#Override
protected Void doInBackground(Void... voids) {
String[] customerInfo = getRegistrationInfo();
// Post
// Send info to tmiszone
String url = "http://SERVER_ADDRESS/"; // I had to add index.php to my url to get around the issue.
client = new DefaultHttpClient();
post = new HttpPost(url);
// Set post parameters
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("salesCode", customerInfo[0]));
pairs.add(new BasicNameValuePair("firstName", customerInfo[1]));
pairs.add(new BasicNameValuePair("lastName", customerInfo[2]));
try {
post.setEntity(new UrlEncodedFormEntity(pairs));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
// Make connection
try {
response = client.execute(post);
} catch (ClientProtocolException e){
// TODO handle
response = null;
} catch (IOException e) {
// TODO handle
response = null;
} catch (Exception e) {
// TODO handle
response = null;
}
return null;
}
Here is my php code.
<html>
<body>
<?php
error_log("hit by app");
foreach($_POST as $key=>$value){
error_log("// ".$key." ".$value);
}
?>
</body>
</html>
Now in my apache log I see the "hit by app" message, but nothing else. And my app gets an empty html page with just the html and body tags as expected from the php code.
The problem I faced had to do with my URL. my url was like
http://ip_address/testbed
the page I was hitting was index.php inside the testbed directory. Since I didn't put trailing "/" apache wasn't sending the parameters to the page during the automatic redirect. Add the "/" resolved the issue. Thank you Sam_D for your help.
I'm trying to increase my knowledge to Android and trying to code a small app for my personal needs.
I'm trying to post data via the HTTP Post method on a test server.
The request is sent ok, but now, I'm trying to display the response, which is an HTML page with the dump of my request.
Here is an extract of my code, it is basically a few EditText fields, and button that sends the request.
The following code is the listener for that button.
validateButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://posttestserver.com/post.php?dump&html&dir=mydir&status_code=200");
try {
// Gathering data
String value01 = nb01Spinner.getSelectedItem().toString();
String value02 = nb02EditText.getText().toString();
String value03 = nb03EditText.getText().toString();
String value04 = nb04EditText.getText().toString();
// Add data to value pairs
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(04);
nameValuePairs.add(new BasicNameValuePair("test01", value01));
nameValuePairs.add(new BasicNameValuePair("test02", value02)); //
nameValuePairs.add(new BasicNameValuePair("test03", value03));
nameValuePairs.add(new BasicNameValuePair("test04", value04));
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
}
I'm not sure if I need to create another Activity or not... I suppose I also have to create a webview aswell, but I'm a bit lost. For now the "raw" HTML would be fine, but afterwards I will need to parse the data, and extract only the strings I need.
So I would need help (an a good and simple example !)
Thank you.
String ret = EntityUtils.toString(response.getEntity());
Maybe this will help?
Very simple approach is Take textview the way you have taken button widget. and what ever response you got set in the textview. you will be able to see the response. else use the Log to log your response in the logcat.
This is how you get the Http response :
byte[] buffer = new byte[1024];
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://www.rpc.booom.com");
postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("params","1"));
//.......
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
HttpResponse response = httpclient.execute(httppost);
Log.w("Response ","Status line : "+ response.getStatusLine().toString());
buffer = EntityUtils.toString(response.getEntity()).getBytes();
I am using:
Log.d("log_response", response.getStatusLine().toString());