I've seen more questions like this but didn't manage to make any sense of them or they didn't apply to my problem, so here goes.
I have an Activity that allows you to login and another where you send POST and GET requests and so on, using your login credentials.
mainActivity:
public class MainActivity extends Activity
{
private String username;
private String password;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText usernameField = (EditText) findViewById(R.id.enterUsername);
final EditText passwordField = (EditText) findViewById(R.id.enterPassword);
Button startButton = (Button) findViewById(R.id.startButton);
startButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
username = usernameField.getText().toString();
password = passwordField.getText().toString();
Intent myIntent = new Intent(view.getContext(), HttpGetPost.class);
startActivityForResult(myIntent, 0);
}
});
}
public String getUser() { return this.username; }
public String getPassword() { return this.password; }
}
HttpGetPost:
public class HttpGetPost extends Activity
{
private MainActivity mainProxy = new MainActivity();
private Button postButton;
private Button getButton;
private Button getMeasureButton;
private Button getDevicesButton;
private String access_token;
private String refresh_token;
private String device_list;
private String expires_in;
private String getRequest;
private static final String TAG = "MyActivity";
private static final String USER_AGENT = "Mozilla/5.0";
private String clientID = some_id;
private String clientSecret = some_secret;
private String user = mainProxy.getUser();
private String pass = mainProxy.getPassword();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_http);
Log.v(TAG, "mainProxy.username: "+user);
Log.v(TAG, "mainProxy.password: "+pass);
postButton = (Button) findViewById(R.id.postButton);
postButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
new sendPost().execute("");
}
});
}
private class sendPost extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... params)
{
try
{
String url = some_url;
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add request header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String urlParameters = "grant_type=password&client_id=" +clientID +"&client_secret="
+clientSecret +"&username=" +user +"&password=" +pass;
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
Log.v(TAG, "\nSending 'POST' request to URL : " + url);
Log.v(TAG, "Post parameters : " + urlParameters);
Log.v(TAG, "Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
Log.v(TAG, response.toString());
if (responseCode == 200)
{
access_token = response.substring(17, 74);
refresh_token = response.substring(93,150);
expires_in = response.substring(165, 170);
getRequest = "http://api.netatmo.net/api/getuser?access_token=" +access_token + " HTTP/1.1";
Log.v(TAG, "access token: " +access_token);
Log.v(TAG, "refresh token: " +refresh_token);
Log.v(TAG, "expires in: " +expires_in);
}
}
catch(Exception e){
e.printStackTrace();
}
return "";
}
protected void onPostExecute(String result) {
Toast.makeText(getApplicationContext(), "ENDED", Toast.LENGTH_LONG).show();
}
}
}
When I print out the username and password in the second class, they both return null, and the POST request fails.
To clarify what I meant in the comment at jbihan's answer:
I'm updating your code:
First revision:
Button startButton = (Button) findViewById(R.id.startButton);
startButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
username = usernameField.getText().toString();
password = passwordField.getText().toString();
Intent myIntent = new Intent(view.getContext(), HttpGetPost.class);
// ADDITION
myIntent.putExtra("username", username);
myIntent.putExtra("password", password);
// END ADDITION
startActivityForResult(myIntent, 0);
}
});
Second revision:
postButton = (Button) findViewById(R.id.postButton);
// ADDITION
final String user = getIntent().getStringExtra("username");
final String password = getIntent().getStringExtra("password");
// END ADDITION
postButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
// EDITED
new sendPost().execute(user, password);
}
});
Third revision:
private class sendPost extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... params)
{
// ADDITION
String user = params[0];
String password = params[1];
// END ADDITION
// use them in the request
// rest of code...
}
}
Please consider using constants for "username" and "password" keys.
You should pass the username and password to your activity using the putExtra methods of the intent :
Intent myIntent = new Intent(view.getContext(), HttpGetPost.class);
myIntent.putExtra("username", username);
myIntent.putExtra("password", pasword);
startActivityForResult(myIntent, 0);
In your second activity, in onCreate() (after setContentView for example), you can retrieve them using getXXExtras :
Intent intent = getIntent();
String username = intent.getStringExtra("username");
String password = intent.getStringExtra("password");
Try to use extras:
Intent myIntent = new Intent(view.getContext(), HttpGetPost.class);
myIntent.putExtra("username", username);
myIntent.putExtra("password", password);
startActivityForResult(myIntent, 0);
In the other actvity(your HttpGetPost)
String user = getIntent().getStringExtra("username");
String password = getIntent().getStringExtra("password");
Here is a nice tutorial about the proper use of Intents.
Try this call of the HttpGetPost Activity:
Intent myIntent = new Intent(this, HttpGetPost.class);
myIntent.putExtra("username", username);
myIntent.putExtra("password", password);
startActivity(myIntent);
With this you pass the right Context in the Intent constructor. Put the data in the Intent which you wanna send to the Activity. The next point is to not call startActivityForResult(), which is used to call an Activity, make some calculation and send the results back to the requesting Activity.
Now get the data out of the Intent in the HttpGetPost Activity like this in your onCreate and save it to a field:
getIntent().getExtras().getString("username");
getIntent().getExtras().getString("password");
You don't need
private MainActivity mainProxy = new MainActivity();
in HttpGetPost. It will create a new MainActivity, which is not the original one which start HttpGetPost.
You can use extras to send data across intents. Here is my solution:
Put this in MainActivity
Intent myIntent = new Intent(view.getContext(), HttpGetPost.class);
myIntent.putExtra(HttpGetPost.KEY_USERNAME, username);
myIntent.putExtra(HttpGetPost.KEY_PASSWORD, password);
startActivityForResult(myIntent, 0);
This is for HttpGetPost, KEY_USERNAME and KEY_PASSWORD can be used to store extra key, so that you can avoid typo.
public static final String KEY_USERNAME = "username"; // or whatever you like for key
public static final String KEY_PASSWORD = "password"; // or whatever you like for key
private String user; // instead of private String user = mainProxy.getUser();
private String pass; // instead of private String pass = mainProxy.getPassword();
Put this in onCreate of HttpGetPost to get the data from intent
Intent intent = getIntent();
user = intent.getStringExtra(KEY_USERNAME);
pass = intent.getStringExtra(KEY_PASSWORD);
Here is the official document for intent.
Related
I'm facing problem in getting a response back in android from PHP.
First, it gets the right response in try then I don't know what cause problem it goes to catch and change response to null. My PHP files are perfectly working I tested them by giving default values.
Below is the code:
This class is used to connect to server and send data to PHP:
public class DatabaseFunctionality extends AsyncTask <String, String, String>{
int flag;
Context context;
String username;
String password;
String rname;
String city;
int mnum;
String sname;
String area;
String sadd;
int snum1;
int snum2;
String cpic;
String ppic;
Bitmap coverpic, profpic;
public String resp;
//public String r;
StringBuilder sb;
public DatabaseFunctionality(Context context, int f){
this.context=context;
this.flag=f;
}
#Override
protected String doInBackground(String... params) {
if(this.flag==0){
username=params[0];
password=params[1];
resp = login();
}
else if(this.flag==1){
rname = params[0];
username = params[1];
password = params[2];
city = params[3];
mnum = Integer.parseInt(params[4]);
sname = params[5];
area = params[6];
sadd = params[7];
snum1 = Integer.parseInt(params[8]);
snum2 = Integer.parseInt(params[9]);
resp = signup();
}
return resp;
}
public String login() {
try {
String link = "http://192.168.0.105:80/directdukan/login.php";
String data = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
sb = new StringBuilder();
String line = null;
// Read Server Response
while ((line = reader.readLine()) != null) {
sb.append(line);
break;
}
Log.e("string", sb.toString());
return sb.toString();
}
catch (Exception e) {
return new String("Exception: " + e.getMessage());
}
}
public String signup(){
try{
String link = "http://192.168.0.105:80/directdukan/signup.php?rname="+rname+"&username="+username+"&password="+password+"&city="+city+"&mnum="+mnum+"&sname="+sname+"&area="+area+"&sadd="+sadd+"&sanum1="+snum1+"&snum2="+snum2;//+"& cpic="+coverpic+"& ppic="+profpic;
URL url = new URL(link);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(link));
HttpResponse response = client.execute(request);
BufferedReader in = new BufferedReader(new
InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line="";
while ((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
Log.e("string", sb.toString());
return sb.toString();
} catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
public void addproduct(){
}
public void searchproduct(){
}
public void editproduct(){
}
public void deleteproduct(){
}
#Override
protected void onPostExecute(String result){
this.resp = result;
}
public Bitmap StringToBitMap(String encodedString){
try {
byte [] encodeByte=Base64.decode(encodedString, Base64.DEFAULT);
Bitmap bitmap= BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
return bitmap;
} catch(Exception e) {
e.getMessage();
return null;
}
}
}
// Below LoginActivity & SignupActivity is used to get data from activity and send it to DatabaseFunctionality class
public class LoginActivity extends AppCompatActivity {
EditText username, password;
Button login, signup;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
login = (Button) findViewById(R.id.button_login);
signup = (Button) findViewById(R.id.button_signup);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String uname = username.getText().toString();
String pass = password.getText().toString();
if(!"".equals(uname) && !"".equals(pass)) {
DatabaseFunctionality db = new DatabaseFunctionality(LoginActivity.this,0);
db.execute(uname,pass);
if(db.resp.equals("user exist")) {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
Toast.makeText(getApplicationContext(), "Login Successful", Toast.LENGTH_SHORT).show();
startActivity(intent);
}
else{
Toast.makeText(getApplicationContext(),"Username or Password is incorrect",Toast.LENGTH_LONG).show();
username.setText(null);
password.setText(null);
}
}
else {
Toast.makeText(getApplicationContext(), "Please Enter Username or Password", Toast.LENGTH_LONG).show();
username.setText(null);
password.setText(null);
}
}
});
signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(LoginActivity.this, SignupActivity.class);
startActivity(intent);
}
});
}
}
public class SignupActivity extends AppCompatActivity {
public int PICK_IMAGE_REQUEST = 1;
public Bitmap bitmap;
public Uri filePath;
String imgname;
EditText username, password, ownername, cnic, shopname, shopadd, shopphone, shopphone2, mobile;
TextView cpic, ppic;
Spinner citymenu, areamenu;
Button signup2, ucpic, uppic;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
ownername = (EditText) findViewById(R.id.rname);
shopname = (EditText) findViewById(R.id.shopname);
shopadd = (EditText) findViewById(R.id.shopadd);
shopphone = (EditText) findViewById(R.id.shopphone);
shopphone2 = (EditText) findViewById(R.id.shopphone2);
mobile = (EditText) findViewById(R.id.mobile);
citymenu =(Spinner) findViewById(R.id.citymenu);
areamenu = (Spinner) findViewById(R.id.areamenu);
cpic = (TextView) findViewById(R.id.coverpic);
ppic = (TextView) findViewById(R.id.profpic);
signup2 = (Button) findViewById(R.id.signup2);
ucpic = (Button) findViewById(R.id.uploadcpicb);
uppic = (Button) findViewById(R.id.uploadppicb);
ucpic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
imgname = getStringImage(bitmap);
cpic.setText(imgname);
}
});
uppic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
imgname = getStringImage(bitmap);
ppic.setText(imgname);
}
});
signup2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String uname = username.getText().toString();
String pass = password.getText().toString();
String rname = ownername.getText().toString();
String city = citymenu.getSelectedItem().toString();
String mnum = mobile.getText().toString();
String sname = shopname.getText().toString();
String area = areamenu.getSelectedItem().toString();
String sadd = shopadd.getText().toString();
String snum1 = shopphone.getText().toString();
String snum2 = shopphone2.getText().toString();
if(!"".equals(rname) && !"".equals(city) && !"".equals(uname) && !"".equals(pass) && !"".equals(sname) && !"".equals(mnum) && !"".equals(area) && !"".equals(sadd) && !"".equals(snum1)) {
DatabaseFunctionality db = new DatabaseFunctionality(SignupActivity.this, 1);
db.execute(rname,uname,pass,city,mnum,sname,area,sadd,snum1,snum2);
if(db.resp.equals("Signup Successful")) {
Intent intent = new Intent(SignupActivity.this, MainActivity.class);
startActivity(intent);
Toast.makeText(SignupActivity.this, "Signup Successful!",
Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getApplicationContext(),"Fields with * are must",Toast.LENGTH_LONG).show();
}
}
else{
Toast.makeText(getApplicationContext(),"Fields with * are must",Toast.LENGTH_LONG).show();
}
}
});
String[] items = new String[]{"*Select","Abbottabad",
"Adezai",
"Ali Bandar",
"Amir Chah",
/* snip */
"Wazirabad",
"Yakmach",
"Zhob",
"Other"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, items);
citymenu.setAdapter(adapter);
String[] items2 = new String[]{"*Select","Johar Town","Faisal Town", "Main Boulevard","Cantt","Model Town"};
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, items2);
areamenu.setAdapter(adapter2);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
}
So each time I run the app, type in an ID and hit submit; the end result come outs with null as the ID.
For example: I want to type in 12345 it should go to http://www.hiddenlink.com/12345 but instead it goes to http://www.hiddenlink.com/null
Here's my code:
public class SearchActivity extends Activity {
Button btnSearchStudent;
String studentID;
private String url = "http://www.hiddenlink.com/" + studentID; // This is test SID just to confirm connection
private static final String TAG_ALLRECORDS = "Objects";
private static final String TAG_ENAME = "emer_name1";
private static final String TAG_EPHONE1 = "emer_Phone1";
private static final String TAG_EPHONE2 = "emer_Phone2";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
EditText txtStudentID = (EditText) findViewById(R.id.txtStudentID);
studentID = txtStudentID.getText().toString();
btnSearchStudent = (Button) findViewById(R.id.btnSearchSID);
btnSearchStudent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(SearchActivity.this, SearchResults.class);
startActivity(intent);
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<Void, Void, Void> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SearchActivity.this);
pDialog.setMessage("Connection Test: Logging into Student Database...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
// Login to APIs
#Override
protected Void doInBackground(Void... args) {
String _username = "hidden";
String _password = "hidden123";
String content = MyHttpURLConnection.getData(url, _username, _password);
try {
// Getting JSON Object from URL Content
JSONObject json = new JSONObject(content);
JSONArray jsonArray = json.getJSONArray(TAG_ALLRECORDS);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
// Storing JSON item in a Variable
String emer_name1 = c.getString(TAG_ENAME);
String emer_Phone1 = c.getString(TAG_EPHONE1);
String emer_Phone2 = c.getString(TAG_EPHONE2);
// Adding value HashMap key => value
HashMap<String, String> add = new HashMap<String, String>();
add.put(TAG_EPHONE1, emer_Phone1);
add.put(TAG_ENAME, emer_name1);
add.put(TAG_EPHONE2, emer_Phone2);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
}
String studentID;
private String url = "http://www.hiddenlink.com/" + studentID;
studentID hasn't been initialized here yet, and so its value is null. Remove the + studentID part and add the studentID when you have set it a value.
#Emd4600 is right
You must add the value only after edittext has been initialized and you have some value in it...
To do so do this just define the "url" var, but don't add student id to it:
private String url = "http://www.hiddenlink.com/%s";
And later when you get edittext do this add the id to url:
EditText txtStudentID = (EditText) findViewById(R.id.txtStudentID);
[... more code...]
String realUrl = String.format(url, txtStudentID.getText().toString(););
That's about it.
Why don't you just change your code with:
private String baseUrl = "http://www.hiddenlink.com/";
private String url = "";
btnSearchStudent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
url = baseUrl + txtStudentID.getText().toString();
new JSONParse().execute();
}
});
I'm missing the sense of reloding the whole Activity
You aren't re-assinging studentID after you click the button, hence it stays null because of its basic initialization:
btnSearchStudent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// re-init the student id field
CharSequence input = txtStudentId.getText();
if (input != null) {
studentID = input.toString();
}
Intent intent = new Intent(SearchActivity.this, SearchResults.class);
startActivity(intent);
new JSONParse().execute();
}
});
Code Standard
You should also label your global variables as m<Name> this is standard to signify that the field is a class member variable
Recommendation
Another way you can do this is to pass in the String into the execute() method of the AsyncTask, that way you can pass in multiple arguments instead of just one, but this will require that you change your AsyncTask to handle multiple queries.
As Emd4600 wrote, your String studentID is not initialized at the moment. You probably want to build and run your request when the user hits btnSearchStudent. To do so, you'll have to append the content of txtStudentId in the onClick listener of your button.
I used what Filnik said and it worked.
Thanks for all the input guys, much appreciated.
Filnik:
private String baseUrl = "http://www.hiddenlink.com/";
private String url = "";
btnSearchStudent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
url = baseUrl + txtStudentID.getText().toString();
new JSONParse().execute();
}
});
I'm doing linkedin integration for sharing the data in android, after giving the username and password and clicked on "sign in and allow" button i'm not able to move to the next page instead coming back to the previous page, and also data not posted on the wall, i tried out many tutorials, links, but could not findout my mistake and struggling alot, can anyone please help me.
here's my MainActivity code
public class MainActivity extends Activity {
public static final String CONSUMER_KEY = "key";
public static final String CONSUMER_SECRET = "secret";
public static final String APP_NAME = "rebuix";
public static final String OAUTH_CALLBACK_SCHEME = "x-oauthflow-linkedin";
public static final String OAUTH_CALLBACK_HOST = "litestcalback";
public static final String OAUTH_CALLBACK_URL = OAUTH_CALLBACK_SCHEME + "://" + OAUTH_CALLBACK_HOST;
LinkedInOAuthService oAuthService = LinkedInOAuthServiceFactory
.getInstance().createLinkedInOAuthService(CONSUMER_KEY,
CONSUMER_SECRET);
LinkedInApiClientFactory factory = LinkedInApiClientFactory
.newInstance(CONSUMER_KEY, CONSUMER_SECRET);
LinkedInRequestToken liToken;
LinkedInApiClient client;
#SuppressLint({ "NewApi", "NewApi", "NewApi" })
Button btnLinkedin;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
Button btnLinkedinMain = (Button) findViewById(R.id.btnLinkedin);
btnLinkedinMain.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (v.getId() == R.id.btnLinkedin) {
oAuthService = LinkedInOAuthServiceFactory.getInstance()
.createLinkedInOAuthService(Constants.CONSUMER_KEY,
Constants.CONSUMER_SECRET);
System.out.println("oAuthService : " + oAuthService);
factory = LinkedInApiClientFactory.newInstance(
Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET);
liToken = oAuthService
.getOAuthRequestToken(Constants.OAUTH_CALLBACK_URL);
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(liToken
.getAuthorizationUrl()));
i.putExtra( "sms_body", false );
try
{
startActivity(i);
} catch (ActivityNotFoundException e) {
// Display some sort of error message here.
}
}
}
protected void onNewIntent(Intent intent) {
try {
linkedInImport(intent);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
private void linkedInImport(Intent intent) {
String verifier = intent.getData().getQueryParameter("oauth_verifier");
System.out.println("liToken " + liToken);
System.out.println("verifier " + verifier);
LinkedInAccessToken accessToken = oAuthService.getOAuthAccessToken(
liToken, verifier);
client = factory.createLinkedInApiClient(accessToken);
// client.postNetworkUpdate("LinkedIn Android app test");
Person profile = client.getProfileForCurrentUser(EnumSet.of(
ProfileField.ID, ProfileField.FIRST_NAME,
ProfileField.LAST_NAME, ProfileField.HEADLINE));
System.out.println("First Name :: " + profile.getFirstName());
System.out.println("Last Name :: " + profile.getLastName());
System.out.println("Head Line :: " + profile.getHeadline());
};
});
}
}
try out this tutorial...you will get message post feature in this tutorial..and for step by step integration in your app see this link... http://code.google.com/p/socialauth-android/wiki/Linkedin
https://github.com/srivastavavivek1987/LinkedIn-Connection-in-Android
I have to develop a login form android application.Here, i have to enter the username and password. If it is correct, fetch the email belonging to the username and display it in the textview and if the username and password is wrong, display login failed message.
This is my webservice code:
public class Login {
public String authentication(String username,String password) {
String retrievedUserName = "";
String retrievedPassword = "";
String retrievedEmail = "";
String status = "";
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/xcart-432pro","root","");
PreparedStatement statement = con.prepareStatement("SELECT * FROM xcart_customers WHERE login = '"+username+"'");
ResultSet result = statement.executeQuery();
while(result.next()){
retrievedUserName = result.getString("login");
retrievedPassword = result.getString("password");
retrievedEmail = result.getString("email");
}
if(retrievedUserName.equals(username)&&retrievedPassword.equals(password)&&!(retrievedUserName.equals("") && retrievedPassword.equals(""))){
status = "Success";
}
else {
status = "Login fail!!!";
}
}
catch(Exception e){
e.printStackTrace();
}
return status;
}
};
This is my android code:
public class CustomerLogin extends Activity {
private static final String SPF_NAME = "vidslogin";
private static final String USERNAME = "login";
private static final String PASSWORD = "password";
private static final String PREFS_NAME = null;
CheckBox chkRememberMe;
private String login;
String mGrandTotal,total,mTitle;
EditText username,userPassword;
private final String NAMESPACE = "http://xcart.com";
private final String URL = "http://10.0.0.75:8085/XcartLogin/services/Login?wsdl";
private final String SOAP_ACTION = "http://xcart.com/authentication";
private final String METHOD_NAME = "authentication";
private String uName;
/**Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.customer_login);
Bundle b = getIntent().getExtras();
total = b.getString("GrandTotal");
mTitle = b.getString("Title");
TextView grandtotal = (TextView) findViewById(R.id.grand_total);
grandtotal.setText("Welcome ," + mTitle );
chkRememberMe = (CheckBox) findViewById(R.id.rempasswordcheckbox);
username = (EditText) findViewById(R.id.tf_userName);
userPassword = (EditText) findViewById(R.id.tf_password);
SharedPreferences loginPreferences = getSharedPreferences(SPF_NAME, Context.MODE_PRIVATE);
username.setText(loginPreferences.getString(USERNAME, ""));
userPassword.setText(loginPreferences.getString(PASSWORD, ""));
Button login = (Button) findViewById(R.id.btn_login);
login.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
loginAction();
}
});
}
private void loginAction(){
boolean isUserValidated = true;
boolean isPasswordValidated = true;
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
EditText username = (EditText) findViewById(R.id.tf_userName);
String user_Name = username.getText().toString();
EditText userPassword = (EditText) findViewById(R.id.tf_password);
String user_Password = userPassword.getText().toString();
//Pass value for userName variable of the web service
PropertyInfo unameProp =new PropertyInfo();
unameProp.setName("username");//Define the variable name in the web service method
unameProp.setValue(user_Name);//set value for userName variable
unameProp.setType(String.class);//Define the type of the variable
request.addProperty(unameProp);//Pass properties to the variable
//Pass value for Password variable of the web service
PropertyInfo passwordProp =new PropertyInfo();
passwordProp.setName("password");
passwordProp.setValue(user_Password);
passwordProp.setType(String.class);
request.addProperty(passwordProp);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try{
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
String status = response.toString();
TextView result = (TextView) findViewById(R.id.tv_status);
result.setText(response.toString());
if(status.equals("Success")) {
// ADD to save and read next time
String strUserName = username.getText().toString().trim();
String strPassword = userPassword.getText().toString().trim();
if (null == strUserName || strUserName.length() == 0) {
// showToast("Enter Your Name");
username.setError( "username is required!" );
isUserValidated = false;
}
if (null == strPassword || strPassword.length() == 0) {
// showToast("Enter Your Password");
isPasswordValidated = false;
userPassword.setError( "password is required!" );
}
if (isUserValidated = true && isPasswordValidated == true) {
if (chkRememberMe.isChecked()) {
SharedPreferences loginPreferences = getSharedPreferences(SPF_NAME, Context.MODE_PRIVATE);
loginPreferences.edit().putString(USERNAME, strUserName).putString(PASSWORD, strPassword).commit();
}
else {
SharedPreferences loginPreferences = getSharedPreferences(SPF_NAME, Context.MODE_PRIVATE);
loginPreferences.edit().clear().commit();
}
}
if (isUserValidated && isPasswordValidated) {
Intent intent = new Intent(CustomerLogin.this,PayPalIntegrationActivity.class);
intent.putExtra("GrandTotal", total);
intent.putExtra("Title", mTitle);
intent.putExtra("login",username.getText().toString());
startActivity(intent);
}
}
else {
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.toast_custom_layout,
(ViewGroup) findViewById(R.id.toast_layout_root));
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.TOP, 0, 30);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
}
}
catch(Exception e){
}
}
}
If the login is success, it will have to display the email on textview. How can i do that?
You can use asy task to do this,
in doInBackground
Do your login operations. Asyctask makes this operation in another task.
when complated in onPostExecute
show the success message. But you need to use runOnUiThread because you cant reach ui controls from non ui thread.
private class loginTask extends AsyncTask<URL, Integer, int> {
protected Long doInBackground(URL... urls) {
// start login process
return 1;
}
protected void onPostExecute(int result) {
_activity.runOnUiThread(new Runnable() {
#Override
public void run() {
textview.setText("login success");
}
});
}
}
I am sending details to be stored in a database using a web service using KSOAP. I have used visual studio to create the web service. The web service works fine. A string will be returned when the details have been inserted into the database. The problem is that this string is empty, maybe something is wrong in the way that i am getting the response. I have been trying to find out whats wrong for a long time. please help
public class Registration extends Activity{
private static final String SOAP_ACTION = "http://tempuri.org/register";
private static final String OPERATION_NAME = "register";
private static final String WSDL_TARGET_NAMESPACE = "http://tempuri.org/";
private static final String SOAP_ADDRESS = "http://10.0.2.2:58076/WebSite1/Service.asmx";
Button sqlRegister, sqlView;
EditText sqlFirstName,sqlLastName,sqlEmail,sqlMobileNumber,sqlCurrentLocation,sqlUsername,sqlPassword;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.registration);
sqlFirstName = (EditText) findViewById(R.id.etFname);
sqlLastName = (EditText) findViewById(R.id.etLname);
sqlEmail = (EditText) findViewById(R.id.etEmail);
sqlMobileNumber = (EditText) findViewById(R.id.etPhone);
sqlCurrentLocation = (EditText) findViewById(R.id.etCurrentLoc);
sqlUsername = (EditText) findViewById(R.id.etUsername);
sqlPassword = (EditText) findViewById(R.id.etPwd);
sqlRegister = (Button) findViewById(R.id.bRegister);
sqlRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
switch (v.getId()){
case R.id.bRegister:
new LongOperation().execute("");
break;
}
}
});
}
private class LongOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String firstname = sqlFirstName.getText().toString();
String lastname = sqlLastName.getText().toString();
String emailadd = sqlEmail.getText().toString();
String number = sqlMobileNumber.getText().toString();
String loc = sqlCurrentLocation.getText().toString();
String uname = sqlUsername.getText().toString();
String pwd = sqlPassword.getText().toString();
SoapObject Request = new SoapObject(WSDL_TARGET_NAMESPACE,OPERATION_NAME);
Request.addProperty("fname", String.valueOf(firstname));
Request.addProperty("lname", String.valueOf(lastname));
Request.addProperty("email", String.valueOf(emailadd));
Request.addProperty("num", String.valueOf(number));
Request.addProperty("loc", String.valueOf(loc));
Request.addProperty("username", String.valueOf(uname));
Request.addProperty("password", String.valueOf(pwd));
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(Request);
HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS);
Log.d("work","work");
try
{
httpTransport.call(SOAP_ACTION, envelope);
SoapObject response = (SoapObject)envelope.getResponse();
String result = response.getProperty(0).toString();
Log.d("res",result);
if(result.equals("reg"))
{
Log.d("reg","reg");
return "Registered";
}
else
{
Log.d("no","no");
return "Not Registered";
}
}catch(Exception e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
Log.d("tag","onpost");
if(result!=null)
{
if(result.equals("Registered"))
{
Toast.makeText(Registration.this, "You have been registered Successfully", Toast.LENGTH_LONG).show();
}
else if(result.equals("Not Registered"))
{
Toast.makeText(Registration.this, "Try Again", Toast.LENGTH_LONG).show();
}
}
else
{
Toast.makeText(Registration.this, "Somethings wrong", Toast.LENGTH_LONG).show(); ///This is what gets printed on screen
}
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
}
Your webservice is returning a String.
Try using this to solve your problem
Object result = envelope.getResponse();
when your webservice return values of type byte[] ,you can do this:
SoapObject response=(SoapObject)envelope.bodyIn;
Hope it helps