http request and http response in android? - android

I am working on with:
org.apache.http.HttpResponse;
org.apache.http.client.HttpClient;
org.apache.http.client.methods.HttpGet;
org.apache.http.impl.client.DefaultHttpClient;
i am using jsp for writing server side code.
i am unaware of the procedure of sending some value to server from my emulator.
and get a value o a string from the server response.
I mean to say... what are the methods to be used? How to use them.?

To send a HTTP GET request and retrieve response:
private static void get(final Context context, final String url) {
new Thread() {
#Override
public void run() {
HttpClient client = new DefaultHttpClient();
HttpGet request = Utils.createHttpRequest(context, url, true, false);
setProxyIfNecessary(context, request);
try {
HttpResponse response = client.execute(request);
Log.v("Test", "StatusCode: " + response.getStatusLine().getStatusCode() + ", Entity: " + EntityUtils.toString(response.getEntity()));
} catch (Exception e) {
// Oh, crash
}
}
}.start();
}
private static void setProxyIfNecessary(Context context, HttpUriRequest request) {
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivity == null ? null : connectivity.getActiveNetworkInfo();
if (networkInfo == null || networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
return;
}
String proxyHost = Proxy.getHost(context);
if (proxyHost == null) {
return;
}
int proxyPort = Proxy.getPort(context);
if (proxyPort < 0) {
return;
}
HttpHost proxy = new HttpHost(proxyHost, proxyPort);
ConnRouteParams.setDefaultProxy(request.getParams(), proxy);
}
Call it by:
get(context, "http://developer.android.com/index.html");
And you will get log by logcat *:S Test:V
Notice that the new thread is to avoid blocking UI thread

Below is a code i implemented for sending username and password from android to server side JSP page. The response from the server is a json object which is then processed.The code is as given below.
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Login_Menu extends Activity {
EditText usname;
EditText pass;
TextView tv;
HttpClient client;
HttpPost post;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_lay);
tv=(TextView) findViewById(R.id.login_stat_tv);
usname=(EditText)findViewById(R.id.uname);
pass=(EditText)findViewById(R.id.pass);
Button login=(Button)findViewById(R.id.login_but);
Button cancel=(Button)findViewById(R.id.cancel_but);
client = new DefaultHttpClient();
String url="http://10.0.2.2:7001/proj/login.jsp";
post = new HttpPost(url);
login.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
new login().execute("");
}
});
cancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
usname.getText().clear();
pass.getText().clear();
}
});
}
private class login extends AsyncTask<String, Void, JSONObject>{
ProgressDialog dialog = ProgressDialog.show(Login_Menu.this, "", "Authenticating, Please wait...");
#Override
protected JSONObject doInBackground(String... params) {
Log.i("thread", "Doing Something...");
//authentication operation
try{
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("username",usname.getText().toString()));
pairs.add(new BasicNameValuePair("password",pass.getText().toString()));
post.setEntity(new UrlEncodedFormEntity(pairs));
HttpResponse response = client.execute(post);
int status=response.getStatusLine().getStatusCode();
if(status == 200)
{
HttpEntity e=response.getEntity();
String data=EntityUtils.toString(e);
JSONObject last=new JSONObject(data);
return last;
}
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
protected void onPreExecute(){
//dialog.dismiss();
Log.i("thread", "Started...");
dialog.show();
}
protected void onPostExecute(JSONObject result){
Log.i("thread", "Done...");
String status;
String name;
try {
status= result.getString("status");
name=result.getString("uname");
if(dialog!=null)
{
dialog.dismiss();
}
else{}
if(status.equalsIgnoreCase("yes"))
{
tv.setText("Login Successful...");
Bundle newbundle=new Bundle();
newbundle.putString("uname",name);
Intent myIntent=new Intent(Login_Menu.this,Instruction.class);
myIntent.putExtras(newbundle);
startActivity(myIntent);
}
else{
tv.setText("No User Found, please try again!");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}

Related

how to call method in login page

i'm currently trying to make a validation for a login page, which is to validate whether the account is in my database or not, i'm to call the method of invokelogin(), but it seems but i don't know how to call the method, need some help with it.
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
public class Activity_Login extends Activity{
private Button btnSignIn;
String username;
String pass;
public static final String USER_NAME = "USERNAME";
EditText txtUser;
EditText Pass;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
btnSignIn = (Button) findViewById(R.id.btnSignIn);
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
launchActivity3();
}
});
}
public void launchActivity3() {
txtUser = (EditText) findViewById(R.id.txtUser);
Pass = (EditText) findViewById(R.id.txtPass);
if (txtUser.getText().toString().equals("")) {
Toast.makeText(Activity_Login.this, "UserName must Be Filled", Toast.LENGTH_SHORT).show();
} else if (Pass.getText().toString().equals("")) {
Toast.makeText(Activity_Login.this, "Password must be Filled", Toast.LENGTH_SHORT).show();
} else {
invokeLogin();
}
Intent intent_SignIn = new Intent(Activity_Login.this, Activity_Drawer2.class);
startActivity(intent_SignIn);
}
public void invokeLogin(View view){
username = txtUser.getText().toString();
pass = Pass.getText().toString();
login(username,pass);
}
private void login (final String username, String pass){
class LoginAsync extends AsyncTask<String, Void, String> {
private Dialog loadingDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(Activity_Login.this, "Please wait", "Loading...");
}
#Override
protected String doInBackground(String... params) {
String uname = params[0];
String pass = params[1];
InputStream is = null;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", uname));
nameValuePairs.add(new BasicNameValuePair("password", pass));
String result = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://10.10.1.11/login.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String result) {
String s = result.trim();
loadingDialog.dismiss();
if (s.equalsIgnoreCase("success")) {
Intent intent = new Intent(Activity_Login.this, Activity_Drawer2.class);
intent.putExtra(USER_NAME, username);
finish();
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "Invalid User Name or Password", Toast.LENGTH_LONG).show();
}
}
}
LoginAsync la = new LoginAsync();
la.execute(username, pass);
}
}
You can pass txtUser and Pass to invokeLogin();
so it look like invokeLogin(txtUser,Pass);
Then your invokeLogin method
public void invokeLogin(String username, String pass){
login(username,pass);
}

Converting DefaultHttpClient to HttpUrlConnection

Hello guys so i'm having difficult in changing this classes that i've created to httpurlConnection. i've seraced the web and im not familiar at all with the httpUrlConnection
App flow:
coming to MainActivity => OnTokenAcuired => GetCokie => Auth
then i have an httpPostRequest
MainActivity:
package com.ap2.demo.comunication;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import com.ap2.demo.R;
import com.ap2.demo.general.SplashActivity;
import org.apache.http.impl.client.DefaultHttpClient;
import java.util.ArrayList;
public class MainActivity extends Activity {
AccountManager accountManager;
private Account[] accounts;
Spinner spinner;
public static DefaultHttpClient httpClient = new DefaultHttpClient();
Account account;
public static String email = "";
ImageView img;
public static boolean enteredOnce = false;
public static String uniqueIDPhone = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
accountManager = AccountManager.get(getApplicationContext());
// assembling all gmail accounts
accounts = accountManager.getAccountsByType("com.google");
// add all gmail accounts :
ArrayList<String> accountList = new ArrayList<String>();
for (Account account : accounts) {
accountList.add(account.name);
}
// setting spinner to be viewed
spinner = (Spinner) findViewById(R.id.account);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, accountList);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
img = (ImageView) findViewById(R.id.splash_door);
//Button startAuth = (Button) findViewById(R.id.startAuth);
img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
spinner = (Spinner) findViewById(R.id.account);
account = accounts[spinner.getSelectedItemPosition()];
email = account.name;
// getIntent().putExtra("task", 1);
accountManager.getAuthToken(account, "ah", null, false,
new OnTokenAcquired(httpClient, MainActivity.this), null);
Intent intent = new Intent(MainActivity.this, SplashActivity.class);
startActivity(intent);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == RESULT_OK) {
accountManager.getAuthToken(account, "ah", null, false,
new OnTokenAcquired(httpClient, MainActivity.this), null);
}
else if(resultCode == RESULT_CANCELED){
// user canceled
}
}
}
OnTokenAcquired:
package com.ap2.demo.comunication;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import com.ap2.demo.enumPackage.Constants;
import org.apache.http.impl.client.DefaultHttpClient;
/**
* Created by Daniel on 19-Jun-15.
*/
/*the result for the auth token request is returned to your application
via the Account Manager Callback you specified when making the request.
check the returned bundle if an Intent is stored against the AccountManager.KEY_INTENT key.
if there is an Intent then start the activity using that intent to ask for user permission
otherwise you can retrieve the auth token from the bundle.*/
public class OnTokenAcquired implements AccountManagerCallback<Bundle> {
private static final int USER_PERMISSION = 989;
private DefaultHttpClient httpclient;
Activity activity;
public OnTokenAcquired(DefaultHttpClient httpclient, Activity activity)
{
this.httpclient = httpclient;
this.activity = activity;
}
#Override
public void run(AccountManagerFuture<Bundle> result) {
Bundle bundle;
try {
bundle = (Bundle) result.getResult();
if (bundle.containsKey(AccountManager.KEY_INTENT)) {
Intent intent = bundle.getParcelable(AccountManager.KEY_INTENT);
intent.setFlags(intent.getFlags() & ~Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivityForResult(intent, USER_PERMISSION);
} else {
setAuthToken(bundle);
}
}
catch(Exception e){
e.printStackTrace();
}
}
//using the auth token and ask for a auth cookie
protected void setAuthToken(Bundle bundle) {
String authToken = bundle.getString(AccountManager.KEY_AUTHTOKEN);
new GetCookie(httpclient, Constants.SERVER_REQUESTS.MY_APP_ID, activity.getBaseContext()).execute(authToken);
}
}
package com.ap2.demo.comunication;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import com.ap2.demo.enumPackage.Constants;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpParams;
import java.io.ByteArrayOutputStream;
/**
* Created by Daniel on 19-Jun-15.
*/
public class GetCookie extends AsyncTask<String, Void, Boolean> {
String appId;
HttpParams params;
private HttpResponse response;
Context context;
private DefaultHttpClient httpclient;
public GetCookie(DefaultHttpClient httpclient, String appId, Context context)
{
this.httpclient = httpclient;
params = httpclient.getParams();
this.appId = appId;
this.context = context;
}
protected Boolean doInBackground(String... tokens) {
try {
// Don't follow redirects
params.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false);
HttpGet httpGet = new HttpGet("http://" + appId
+ ".appspot.com/_ah/login?continue=http://" + appId + ".appspot.com/&auth=" + tokens[0]);
response = httpclient.execute(httpGet);
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
if(response.getStatusLine().getStatusCode() != 302){
// Response should be a redirect
return false;
}
//check if we received the ACSID or the SACSID cookie, depends on http or https request
for(Cookie cookie : httpclient.getCookieStore().getCookies()) {
if(cookie.getName().equals("ACSID") || cookie.getName().equals("SACSID")){
return true;
}
}
} catch (Exception e) {
e.printStackTrace();
cancel(true);
} finally {
params.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true);
}
return false;
}
protected void onPostExecute(Boolean result)
{
new Auth(httpclient, context).execute(Constants.SERVER_REQUESTS.LOGIN);
}
}
package com.ap2.demo.comunication;
import android.content.Context;
import android.os.AsyncTask;
import android.telephony.TelephonyManager;
import android.widget.Toast;
import com.ap2.demo.R;
import com.ap2.demo.enumPackage.Constants;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
/**
* Created by Daniel on 19-Jun-15.
*/
public class Auth extends AsyncTask<String, Void, Boolean> {
private DefaultHttpClient httpclient;
private HttpResponse response;
private String content = null;
Context context;
public Auth(DefaultHttpClient httpclient, Context context)
{
this.httpclient = httpclient;
this.context = context;
}
protected Boolean doInBackground(String... urls) {
try {
HttpGet httpGet = new HttpGet(urls[0]);
response = httpclient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
content = out.toString();
return true;
}
} catch (Exception e) {
e.printStackTrace();
cancel(true);
}
return false;
}
//display the response from the request above
protected void onPostExecute(Boolean result) {
if (content != null) {
try {
System.out.print(result);
JSONObject obj = new JSONObject(content);
String status = obj.getString(Constants.LOGIN_SERVICE.STATUS);
if (status.equals(Constants.LOGIN_SERVICE.LOGIN_STATUS_OF_USER)) {
Toast.makeText(context, R.string.user_already_logged_in_status,
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, R.string.welcome_message,
Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Toast.makeText(context, R.string.failed_to_login + content,
Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(context, R.string.could_not_loged_to_server,
Toast.LENGTH_LONG).show();
}
}
}
now notice im using the same httpclient because of the auth and cockie:
package com.ap2.demo.channels;
import android.app.Activity;
import android.os.AsyncTask;
import com.ap2.demo.comunication.MainActivity;
import com.ap2.demo.enumPackage.Constants;
import com.ap2.demo.main_activity.MapWithMarkers;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Daniel on 30-Jun-15.
*/
public class ServerRequestAddChannel extends AsyncTask<String, String, String> {
Activity activity;
String name;
public ServerRequestAddChannel(Activity activity, String name) {
this.activity = activity;
this.name = name;
}
#Override
protected String doInBackground(String... params) {
HttpPost httppost = new HttpPost(params[0]);
try {
// i have name and path only left id
int idCounter = MapWithMarkers.id_counter++;
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
String name_of_channel = name;
if (name.equals(Constants.REVIEWS_CHANNEL.NAME)) {
// add special id to reviews channel
nameValuePairs.add(new BasicNameValuePair(Constants.REVIEWS_CHANNEL.ID, Constants.REVIEWS_CHANNEL.ID));
} else {
name_of_channel = name + Integer.toString(idCounter);
// taking off all free space for unique id
name_of_channel = name_of_channel.replaceAll(" ","");
nameValuePairs.add(new BasicNameValuePair(Constants.CHANNEL_REQUESTS.CHANNEL_TAG_ID, name_of_channel));
}
nameValuePairs.add(new BasicNameValuePair(Constants.CHANNEL_REQUESTS.CHANNEL_TAG_NAME, name));
nameValuePairs.add(new BasicNameValuePair(Constants.CHANNEL_REQUESTS.CHANNEL_TAG_ICON, ""));
// adding the channel to my new list
if (!name_of_channel.equals(Constants.REVIEWS_CHANNEL.NAME)) {
MapWithMarkers.channels_map.put(name_of_channel, new ChannelItem(name_of_channel, "", name));
MapWithMarkers.my_subscriptions.add(name_of_channel);
}
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = MainActivity.httpClient.execute(httppost);
HttpEntity entity = response.getEntity();
String text = getASCIIContentFromEntity(entity);
return response.getStatusLine().getReasonPhrase().toString();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
return null;
}
protected void onPostExecute(String result) {
((AddChannelActivity) activity).moveToNextIntent();
}
protected String getASCIIContentFromEntity(HttpEntity entity)
throws IllegalStateException, IOException {
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n > 0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n > 0)
out.append(new String(b, 0, n));
}
return out.toString();
}
}
please help..

Android, send string from app to web server

I am trying to make an app where i am supposed to send data from the application to a web server.
So far i've been searching and not been able to find a working example, i've found some using asynctask which does not work, so any help is appreciated!
try below code :-
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import com.hmkcode.android.vo.Person;
public class MainActivity extends Activity implements OnClickListener {
TextView tvIsConnected;
EditText etName,etCountry,etTwitter;
Button btnPost;
Person person;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get reference to the views
tvIsConnected = (TextView) findViewById(R.id.tvIsConnected);
etName = (EditText) findViewById(R.id.etName);
etCountry = (EditText) findViewById(R.id.etCountry);
etTwitter = (EditText) findViewById(R.id.etTwitter);
btnPost = (Button) findViewById(R.id.btnPost);
// check if you are connected or not
if(isConnected()){
tvIsConnected.setBackgroundColor(0xFF00CC00);
tvIsConnected.setText("You are conncted");
}
else{
tvIsConnected.setText("You are NOT conncted");
}
// add click listener to Button "POST"
btnPost.setOnClickListener(this);
}
public static String POST(String url, Person person){
InputStream inputStream = null;
String result = "";
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
String json = "";
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("name", person.getName());
jsonObject.accumulate("country", person.getCountry());
jsonObject.accumulate("twitter", person.getTwitter());
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
// ** Alternative way to convert Person object to JSON string usin Jackson Lib
// ObjectMapper mapper = new ObjectMapper();
// json = mapper.writeValueAsString(person);
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// 10. convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
// 11. return result
return result;
}
public boolean isConnected(){
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
return true;
else
return false;
}
#Override
public void onClick(View view) {
switch(view.getId()){
case R.id.btnPost:
if(!validate())
Toast.makeText(getBaseContext(), "Enter some data!", Toast.LENGTH_LONG).show();
// call AsynTask to perform network operation on separate thread
new HttpAsyncTask().execute("http://hmkcode.appspot.com/jsonservlet");
break;
}
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
person = new Person();
person.setName(etName.getText().toString());
person.setCountry(etCountry.getText().toString());
person.setTwitter(etTwitter.getText().toString());
return POST(urls[0],person);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Data Sent!", Toast.LENGTH_LONG).show();
}
}
private boolean validate(){
if(etName.getText().toString().trim().equals(""))
return false;
else if(etCountry.getText().toString().trim().equals(""))
return false;
else if(etTwitter.getText().toString().trim().equals(""))
return false;
else
return true;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
}
see below link for more info :-
http://hmkcode.com/android-send-json-data-to-server/
http://androidexample.com/How_To_Make_HTTP_POST_Request_To_Server_-_Android_Example/index.php?view=article_discription&aid=64&aaid=89
Try this,
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
public class AdminLogin extends Activity {
EditText adminUN, adminPass;
CheckBox cb;
Button loginBtn;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
// Your IP address or your website complete address
String adminLoginURL = "http://192.168.1.1/admin_login.php";
ProgressDialog dialog = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.admin_login);
loginBtn = (Button) findViewById(R.id.adminLogin);
adminUN = (EditText) findViewById(R.id.adminUName);
adminPass = (EditText) findViewById(R.id.adminPass);
loginBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new Admin_Login().execute();
}
});
}
class Admin_Login extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(AdminLogin.this);
dialog.setMessage("Please Wait..!");
dialog.setIndeterminate(false);
dialog.setCancelable(true);
dialog.show();
}
protected String doInBackground(String... params) {
new Thread(new Runnable() {
public void run() {
login();
}
}).start();
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
dialog.dismiss();
}
}
void login() {
try {
httpclient = new DefaultHttpClient();
httppost = new HttpPost(adminLoginURL);
// add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", adminUN
.getText().toString().trim()));
nameValuePairs.add(new BasicNameValuePair("password", adminPass
.getText().toString().trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
response = httpclient.execute(httppost);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost,
responseHandler);
boolean matches = response.startsWith("User Found");
if (matches) {
// Do something start an Activity or do anything you wanted
}
} else {
showAlert();
}
} catch (Exception e) {
dialog.dismiss();
System.out.println("Exception : " + e.getMessage());
}
}
public void showAlert() {
AdminLogin.this.runOnUiThread(new Runnable() {
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(
AdminLogin.this);
builder.setTitle("Login Error.");
builder.setMessage("User not Found.")
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_exit, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_exit:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Create an .xml file to get the username, password, and login button
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/ic_wall"
android:gravity="center_horizontal"
android:orientation="vertical" >
<EditText
android:id="#+id/adminUName"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_marginTop="50dip"
android:hint="Username"
android:singleLine="true" />
<requestFocus />
<EditText
android:id="#+id/adminPass"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_marginTop="10dip"
android:ems="10"
android:hint="Password"
android:inputType="textPassword"
android:singleLine="true" />
<Button
android:id="#+id/adminLogin"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dip"
android:text="Login"
android:textColor="#0b84aa" />
</LinearLayout>
You must have PhpMyAdmin to try this in local system, if you have hosted server part then try use the following php code and run it.
adminLogin.php
<?php
$hostname_localhost ="";
$database_localhost ="";
$username_localhost ="";
$password_localhost ="";
# Make sure above fields are filled with your config values (must)
$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_localhost, $localhost);
if (empty($_POST['username'])) {
echo "Please Enter a name";
} else {
$username = $_POST['username'];
}
if (empty($_POST['password'])) {
echo "Please Enter Your Password ";
} else {
$password = SHA1($_POST['password']);
}
$query_search = "select * from adminregister where username = '".$username."' AND password = '".$password."'";
$query_exec = mysql_query($query_search) or die(mysql_error());
$rows = mysql_num_rows($query_exec);
//echo $rows;
if($rows == 0) {
echo "\nNo Such User Found";
}
else {
echo "User Found";
}
mysql_close();
?>
Note: You need to create database and table specified in mysql to feed and retrieve the data
If any errors please leave a comment.

Login in android with webservice using json

package com.example.friendfinder;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class login extends Activity implements OnClickListener{
String APIurl = "http://friendfinder.hostzi.com/ws/";
Button btnlogin;
TextView login_user;
TextView login_pass;
TextView tv;
JSONObject jObject;
AlertDialog.Builder builder;
AlertDialog alert;
ProgressDialog progressDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
start();
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_entrar:
if (checkStatus()) {
progressDialog.show();
new Thread(new Runnable() {
public void run() {
try {
jObject = new JSONObject(getJSON("login.php?email="
+ login_user.getText().toString()
+ "&password="
+ login_pass.getText().toString()));
tv.setText(jObject.toString());
Log.e("JSON", jObject.toString());
if (jObject.getString("success").equalsIgnoreCase(
"true")) {
progressDialog.dismiss();
confirm();
} else if (jObject.getString("success")
.equalsIgnoreCase("false")) {
login.this.runOnUiThread(new Runnable() {
#Override
public void run() {
progressDialog.dismiss();
builder.setMessage("O inicio de sessão falhou, verifica os teus dados.");
alert = builder.create();
alert.show();
}
});
login.this.runOnUiThread(null);
} else {
login.this.runOnUiThread(new Runnable() {
#Override
public void run() {
progressDialog.dismiss();
builder.setMessage("O inicio de sessão falhou, verifica os teus dados.");
alert = builder.create();
alert.show();
}
});
login.this.runOnUiThread(null);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
else{
builder.setMessage("Não existe de momento nenhuma conexão à Internet! O ínicio de sessão é impossivel de realizar");
alert = builder.create();
alert.show();
}
}
}
public void start(){
login_user = (TextView) findViewById(R.id.login_user);
login_pass = (TextView) findViewById(R.id.login_pass);
tv = (TextView) findViewById(R.id.tv);
btnlogin = (Button) findViewById(R.id.btn_entrar);
btnlogin.setOnClickListener(this);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("A iniciar sessão...");
builder = new AlertDialog.Builder(login.this);
builder.setCancelable(false);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
}
public void confirm(){
Intent i = new Intent(login.this, maps.class);
startActivity(i);
finish();
}
public String getJSON(String rurl) {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(APIurl + rurl);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} else {
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return builder.toString();
}
public boolean checkStatus() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
}
LogCat
http://pastebin.com/0xVv2pBR
When i click the button to login the app crashes and i realy can't understand what is wrong, if you need more information just ask me. If you know how to resolve help me please.
Thanks
logs says
"02-06 18:50:47.785: I/Choreographer(874): Skipped 41 frames! The application may be doing too much work on its main thread"
if you are new to Android you must learn to implement AsyncTask in your Activity. You are not suppose to use webservice or http communication in main/UI thread. here i found Tutorial to implement AsyncTask please learn it will solve your problem.

android text not visible

I am sending some information from my application to server and waiting for the response. Before i send i set my textview for message to display "processing request" and after getting response i display a different message.
This processing message is not getting displayed. Is it beacuse the UI is getting blocked due to other operation.
How to handle this. Threading is not giving correct result as need to display the response.
SO that involve UI in the thread .
package com.PandG.app.android.activities;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.PandG.app.android.R;
import com.PandG.app.android.dataAccess.SettingsDBAccess;
import com.PandG.app.android.entity.Job;
import com.PandG.app.android.entity.Settings;
import com.PandG.app.android.services.JobsManager;
import com.lib.android.Utils.Utils;
import com.lib.android.activity.BaseActivity;
import com.lib.android.dataAccess.DatabaseManager;
public class JobCheckoutActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setViewContent();
}
private void setViewContent() {
Settings setting = getSettings();
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.job_checkout);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.customtitle);
//new DataProcess().execute(null);
TextView text1 = (TextView)findViewById(R.id.checkoutmessage);
text1.setText("Processiong Job Cart ...");
if(setting!=null){
TextView text2 = (TextView)findViewById(R.id.checkoutheading);
text2.setVisibility(View.GONE);
Button homeButton = (Button)findViewById(R.id.gohome);
homeButton.setVisibility(View.GONE);
JSONObject jobObject =encodeData(setting);
sendDataToServer(jobObject);
}
}
private void sendDataToServer(JSONObject jobObject) {
TextView text1 = (TextView)findViewById(R.id.checkoutmessage);
text1.setText("Processiong Job Cart ...");
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); // Timeout
// Limit
HttpResponse response;
try {
HttpPost post = new HttpPost(Utils.getPostUrl());
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("orderparameters",
jobObject.toString()));
Log.i("Job ORDER", jobObject.toString());
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = client.execute(post);
checkResponseFromServer(response);
ClearCart();
} catch (Exception e) {
Log.w("error", "connection failed");
Toast.makeText(this, "Order not placed due to connection error",
Toast.LENGTH_LONG);
e.printStackTrace();
}
}
private void ClearCart() {
JobsManager.JobsCartList.clear();
}
private void checkResponseFromServer(HttpResponse response) {
try {
if (response != null) {
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(in));
String line;
StringBuffer buffer = new StringBuffer();
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
in.close();
JSONObject jsonResponse = new JSONObject(buffer.toString());
Log.i("Status", jsonResponse.getString("status"));
Log.i("Status", jsonResponse.getString("message"));
Log.i("Status", jsonResponse.getString("debug"));
TextView text1 = (TextView)findViewById(R.id.checkoutheading);
text1.setVisibility(View.VISIBLE);
TextView text = (TextView) findViewById(R.id.checkoutmessage);
if (jsonResponse.getString("status").equals("SUCC")) {
text.setText( Html.fromHtml(getString(R.string.checkout_body1)));
} else
text.setText(jsonResponse.getString("message")
+ jsonResponse.getString("debug"));
}
} catch (Exception ex) {
}
}
private JSONObject encodeData(Settings setting) {
JSONObject jobObject = new JSONObject();
try {
JSONObject jobject = new JSONObject();
jobject.put("name", setting.getName());
jobject.put("email", setting.getEmail());
jobject.put("phone", setting.getPhone());
jobject.put("school", setting.getSchool());
jobject.put("major", setting.getMajor());
jobObject.put("customer", jobject);
JSONArray jobsarray = new JSONArray();
for (Job job : JobsManager.JobsCartList) {
JSONObject jobEntry = new JSONObject();
jobEntry.put("jobtitle",job.getTitle());
jobEntry.put("qty","1");
jobsarray.put(jobEntry);
}
jobObject.put("orders", jobsarray);
} catch (JSONException ex) {
}
return jobObject;
}
private Settings getSettings() {
SettingsDBAccess settingsDBAccess = new SettingsDBAccess(
DatabaseManager.getInstance());
Settings setting = settingsDBAccess.getSetting();
if (setting==null){
startActivityForResult((new Intent(this,SettingsActivity.class)),Utils
.getDefaultRequestCode());
}
return setting;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Settings setting = new SettingsDBAccess(
DatabaseManager.getInstance()).getSetting();
if(setting!=null){
JSONObject jobObject = encodeData(setting);
sendDataToServer(jobObject);
}
}
/* private class DataProcess extends AsyncTask {
#Override
protected void onPostExecute(Object result) {
}
#Override
protected Object doInBackground(Object... arg0) {
processDataandsend();
return null;
}
private void processDataandsend() {
Settings setting = getSettings();
if(setting!=null){
TextView text2 = (TextView)findViewById(R.id.checkoutheading);
text2.setVisibility(View.GONE);
Button homeButton = (Button)findViewById(R.id.gohome);
homeButton.setVisibility(View.GONE);
JSONObject jobObject =encodeData(setting);
sendDataToServer(jobObject);
}
}
} */
}
You should not perform HTTP-work on the UI-thread. Instead use AsyncTask
In your AsyncTask you are only allowed to update the UI in two places:
#Override
protected void onPreExecute()
TextView.setText("Beginning HTTP-work..Please wait");
{
and
#Override
protected void onPostExecute(Void v) {
TextView.setText("Done..SUCCESS!");
}
Use these two to update the UI before and after the HTTP-work has been done.
Long operations must be in background. Best way to implement this on Android, use AsyncTask, for more information: http://developer.android.com/reference/android/os/AsyncTask.html

Categories

Resources