Send data from java android to webserver with post method - java

I want to send data from Java Android to mysql php server.
This is my code for button click:
public void loginPost(View view){
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
String result="";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://geospy.zz.mu/default.php");
try {
List <NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("UserName", username));
nameValuePairs.add(new BasicNameValuePair("PassWord", password));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if (entity != null) {
StringBuilder sb = new StringBuilder();
String line;
InputStream instream = entity.getContent();
BufferedReader bf = new BufferedReader(new InputStreamReader(instream));
while ((line = bf.readLine()) != null ) {
sb.append(line).append("\n");
}
result = sb.toString();
Log.i("Read from server", result);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
status.setText(username);
//Intent intent = new Intent(LoginActivity.this, PembukaActivity.class);
//startActivity(intent);
}
This is my code in login.php:
<?php
include("connect.php");
//define $myusername and $mypassword
$myusername = $_POST['UserName'];
$mypassword = $_POST['PassWord'];
//to protect mysql injection
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$mypassword = $mypassword;
$sql = "SELECT ID_MEMBER FROM MEMBER WHERE USERNAME='".$myusername."' and PASSWORD= '".$mypassword."'";
echo $sql;
$result = mysql_query($sql);
//mysql_num_row is counting table row
$count = mysql_num_rows($result);
echo "<script> alert('".$count."')</script>";
if($count == 1)
{
session_start();
$row = mysql_fetch_array($result);
//$_SESSION['login'] = $myusername;
$_SESSION['id_member'] = $row['id_member'];
header('Location: login.php');
}
else
{
header('Location: default.php');
}
?>
I add this permission in manifest:
<uses-permission android:name="android.permission.INTERNET" />
But the application was stopped after i run it. I don't know where is the error.

Try doing your networking in an ASyncTask so that your networking isnt done on the UIThread, i think thats why your crashing
something like this
class TheTask extends AsyncTask<Void,Void,Void>
{
protected void onPreExecute()
{ super.onPreExecute();
}
protected Void doInBackground(Void ...params)
{
loginPost();//View view); // View view replace
// i think even having view as a parameter will crash
// doinbackground method you have to change it i think
}
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
// Back to UIThread, i think handle status.setText(username);
// from here and take it out of your loginPost() method UI operations will
// crash doInBackground(Void ...params)
}
}
then call it in your code like this
new TheTask().execute();
EDIT: well all of your views and whatnot will crash doinbackground method use on PreExecute and OnpostExecute for begining and ending with UIOperations

You need to use AsyncTask.
public class UserLogin extends AsyncTask<ArrayList<String>, Void, String> {
protected String doInBackground(ArrayList<String>... userdata) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.website.com/script.php");
String result = null;
try{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("email", userdata[0].get(0)));
nameValuePairs.add(new BasicNameValuePair("pass", userdata[0].get(1)));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
InputStream is = response.getEntity().getContent();
String line = "";
StringBuilder total = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
while ((line = rd.readLine()) != null) {
total.append(line);
}
result = total.toString();
}
catch(NoHttpResponseException e){
Log.d("resultLoginError", e.getMessage());
}
catch(Exception e){
Log.d("resultLoginOther", e.toString());
}
return result;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected void onPostExecute(String result) {
Log.d("resultOnLogin", "LOGGED?");
}
}
public String Login(String user, String pass) throws InterruptedException, ExecutionException{
ArrayList<String> userdata = new ArrayList<String>();
userdata.add(user);
userdata.add(pass);
return new UserLogin().execute(userdata).get();
}
This is what I personally use for login.
script.php is a PHP file that handles POST values (Username and password) and sends back confirmation to app.

Related

Changing password of user - Update Database Table PHP/JAVA

I have been trying to make a 'change password' function by myself. Meaning when a user wants to change his password, a dialog will pop up and it shows three fields: Old Password, New Password and Confirm New Password. The old password is taken care of by using SharedPreferences.
public void invokeChangePass WORKS. So you do not have to look at that.
The problem is in the php file and the private void updateDataBase It will not change the password of the user in the database.
Everything aside from the php file and updateDatabase function works so do not worry about that.
Useful notes:
I know it's vulnerable to mysql injection. Not my priority at the moment.
EmailKey and PassKey are made in SharedPreferences when the user logs in.
It is supposed to find the EmailKey in the database, in order to change the password of that user.
It is as a while ago since I made this so it might have dumb mistakes or things I just forgot to add.
Thank you very much.
JAVA FILE:
public class ChangePassDialog extends Activity {
private EditText setOldPass;
private EditText setNewPass;
private EditText setNewPass2;
public static final String MyPREFERENCES = "MyPrefs";
SharedPreferences sharedpreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_changepass);
setOldPass = (EditText) findViewById(R.id.setOldPass);
setNewPass = (EditText) findViewById(R.id.setNewPass);
setNewPass2 = (EditText) findViewById(R.id.setNewPass2);
}
public void invokeChangePass(View view) {
String oldpass = setOldPass.getText().toString();
String pass = setNewPass.getText().toString();
String pass2 = setNewPass2.getText().toString();
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
String passKey = sharedpreferences.getString("passKey", "DEFAULT");
String name = sharedpreferences.getString("emailKey", "DEFAULT");
// onPreExecute();
if (oldpass.equals(passKey) && pass.length() >= 6 && pass.length() <= 30 && (pass2.length() >= 0 && (pass.equals(pass2)) && (!pass.equals(pass.toLowerCase()) &&
!pass.equals(pass.toUpperCase()) &&
pass.matches(".*\\d+.*")))) {
updateDatabase(pass, name);
setNewPass2.requestFocus();
setNewPass2.setError("TEST WORKING.");
} else {
errorTest(oldpass, pass, pass2);
}
}
private void updateDatabase(String pass, String name) {
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String name = params[0];
String pass = params[1];
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("pass", pass));
nameValuePairs.add(new BasicNameValuePair("name", name));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://calisapp.esy.es/changepass.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
InputStream entity = response.getEntity().getContent();
InputStreamReader inputStream = new InputStreamReader(entity);
BufferedReader bufferedReader = new BufferedReader(inputStream);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while ((bufferedStrChunk = bufferedReader.readLine()) != null) {
stringBuilder.append(bufferedStrChunk);
}
return stringBuilder.toString();
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return "";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
String s = result.trim();
if(s.equalsIgnoreCase("success")){
Intent intent = new Intent(ChangePassDialog.this, Settings.class);
startActivity(intent);
Toast.makeText(ChangePassDialog.this, "Registered successfully", Toast.LENGTH_LONG).show();
finish();
}
// loadingDialog.dismiss();
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(name,pass);
}
PHP FILE:
<?php
define('HOST','X');
define('USER','X');
define('PASS','X');
define('DB','X');
$con = mysqli_connect(HOST,USER,PASS,DB);
$name = $_POST['name'];
$pass = $_POST['pass'];
$sql = "UPDATE tbl_user SET password='$pass' WHERE username = '$name'";
if(mysqli_query($con,$sql)){
echo 'success';
}
mysqli_close($con);
?>
First. I don't think it's a good idea to use AsyncTask for that, as it could cause some problems. This is discussed here.
But well, that's not your priority nor your question, so let's get along.
Change this
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
for this
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));
And change this
InputStreamReader inputStream = new InputStreamReader(entity);
BufferedReader bufferedReader = new BufferedReader(inputStream);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while ((bufferedStrChunk = bufferedReader.readLine()) != null) {
stringBuilder.append(bufferedStrChunk);
}
return stringBuilder.toString();
To this
HttpResponse response = httpClient.execute(httpPost);
String resp = EntityUtils.toString(response.getEntity(),"UTF-8");
return resp;
And try to change your php file to this
<?php
define('HOST','X');
define('USER','X');
define('PASS','X');
define('DB','X');
$name = $_POST['name'];
$pass = $_POST['pass'];
if (isset($name) && isset($pass)) {
$mysqli = new mysqli(HOST,USER,PASS,DB);
if ($mysqli->connect_error) {
die('Error while connecting to database!');
}
$sql = "UPDATE tbl_user SET password='" .$pass ."' WHERE username ='" . $name . "'";
$res = $mysqli->query($sql);
if ($res) {
echo "success";
}
$mysqli->close();
}
?>

Attempt to invoke virtual method 'int org.json.JSONObject.getInt(java.lang.String)' on a null object reference

I'm trying to check the username/psw on my phpmyadmin database
but I can't figure out the problem.
The logcat gives me this error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int org.json.JSONObject.getInt(java.lang.String)' on a null object reference
Java code:
public class MainActivity extends ActionBarActivity {
// Progress Dialog
private ProgressDialog pDialog;
private String password="";
private String userName="";
JSONParser jsonParser = new JSONParser();
// url to create new product
private static String url_login = "http://localhost/android_connect/get_login.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
Button btnSignIn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSignIn=(Button)findViewById(R.id.buttonSignIN);
}
public void signIn(View V)
{
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.login);
dialog.setTitle("Login");
// get the Refferences of views
final EditText editTextUserName=(EditText)dialog.findViewById(R.id.editTextUserNameToLogin);
final EditText editTextPassword=(EditText)dialog.findViewById(R.id.editTextPasswordToLogin);
Button btnSignIn=(Button)dialog.findViewById(R.id.buttonSignIn);
// Set On ClickListener
btnSignIn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// get The User name and Password
userName=editTextUserName.getText().toString();
password=editTextPassword.getText().toString();
new LoginUser().execute();
}
});
dialog.show();
}
class LoginUser extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Verificoo NomeUtente & Password ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Checking login
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("use_username", userName));
params.add(new BasicNameValuePair("use_psw", password));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_login,
"POST", params);
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS)
if (success == 1) {
//blablabla
} else {
Intent intent = getIntent();
finish();
Toast.makeText(MainActivity.this, "User Name or Password does not match", Toast.LENGTH_LONG).show();
startActivity(intent);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
#miselking
here the class JsonParser
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if (method == "POST") {
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} else if (method == "GET") {
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
check json is not null
if(json!=null){do something}
Error at this line
httpPost.setEntity(new UrlEncodedFormEntity(params));
Use this line
if (params!=null)
httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
and also in GET method use HTTP.UTF_8 instead of "utf-8"

Send data by method Post? (Android & PHP)

The problem is I cant send data by POST method
None of the codes helped me to pass data through post method, all marked errors when I running
Code:
public class Registro extends Activity{
protected String pagina = "http://192.168.0.5/vcard/index.php";
protected WebView web;
protected String qr = "70", firstname = "Name", lastname = "Last",
email = "email#hotmail.es", institucion = "ITA", movil = "9136161";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
web = (WebView) findViewById(R.id.webView1);
postData();
web.loadUrl(pagina);
}
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(pagina);
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(6);
nameValuePairs.add(new BasicNameValuePair("qr", qr));
nameValuePairs.add(new BasicNameValuePair("firstname", firstname));
nameValuePairs.add(new BasicNameValuePair("lastname", lastname));
nameValuePairs.add(new BasicNameValuePair("email", email));
nameValuePairs.add(new BasicNameValuePair("institucion", institucion));
nameValuePairs.add(new BasicNameValuePair("movil", movil ));
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
}
} }
other code
public class Registro extends Activity{
protected String pagina = "http://192.168.0.5/vcard/index.php";
protected WebView web;
protected String qr = "70", firstname = "Jonatan", lastname = "Flores",
email = "quemeves#hotmail.es", institucion = "ITA", movil = "9136161";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
web = (WebView) findViewById(R.id.webView1);
try
{
HttpURLConnection connection;
OutputStreamWriter request = null;
URL url = null;
String response = null;
String parameters = "qr="+qr+"&firstname="+firstname+"&lastname="+lastname+"&email="
+email+"&institucion="+institucion+"&movil="+movil;
url = new URL(pagina);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestMethod("POST");
request = new OutputStreamWriter(connection.getOutputStream());
request.write(parameters);
request.flush();
request.close();
String line = "";
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
// Response from server after login process will be stored in response variable.
response = sb.toString();
// You can perform UI operations here
Toast.makeText(this,"Message from Server: \n"+ response, 0).show();
isr.close();
reader.close();
}
catch(IOException e)
{
{Toast.makeText(this,"Error 1", 0).show();
}
}
web.loadUrl(pagina);
}}
PHP Data
<?php
require("LBHToolkit/vCard/Generator.php");
$nombres = $_POST['qr']);
$firstname = $_POST['firstname']);
$lastname = $_POST['lastname']);
$email = $_POST['email']);
$institucion = $_POST['institucion']);
$movil = $_POST['movil']);
... //code to generate a vCard
echo $vcard->create();
?>
In the end, the data is obtained and downloads a vCard, but always download a vCard without data
Use AsyncTask class for postData()

JSONException: Value <br of type java.lang.String cannot be converted to JSONObject

I tried hard to search the solution but I still not manage to solve it. Kindly help. Here my java code : -
public class MainActivity extends Activity {
String project_id;
String id;
InputStream is=null;
String result=null;
String line=null;
int code = 0;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText e_id =(EditText) findViewById(R.id.editText1);
final EditText e_prjId =(EditText) findViewById(R.id.editText2);
Button insert =(Button) findViewById(R.id.button1);
id = e_id.getText().toString();
project_id = e_prjId.getText().toString();
insert.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
insert();
}
});
}
public void insert() {
final ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id",id));
nameValuePairs.add(new BasicNameValuePair("Project_Id",project_id));
new Thread(new Runnable() {
public void run() {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.0.111/insert.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
}
catch(Exception e){
Log.e("Fail 1", e.toString());
Toast.makeText(getApplicationContext(), "Invalid IP Address",
Toast.LENGTH_LONG).show();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null){
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
}
catch(Exception e){
Log.e("Fail 2", e.toString());
}
try {
Log.i("tagconvertstr", "["+result+"]");
JSONObject json_data = new JSONObject(result);
code=(json_data.getInt("code"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(code==1)
{
Toast.makeText(getBaseContext(), "Inserted Successfully",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getBaseContext(), "Sorry, Try Again",Toast.LENGTH_LONG).show();
}
}
}).start();
}
php:-
<?php
$uname='root';
$pwd='';
$con = new PDO("mysql:host=192.168.0.111;dbname=wktask", $uname, $pwd);
$ID=$_REQUEST['ID'];
$Project_Id=$_REQUEST['Project_Id'];
$flag['code']=0;
if($r= $con->query("insert into task(ID,Project_Id) values('$ID','$Project_Id')"))
{
$flag['code']=1;
}
echo(json_encode($flag));
?>
I really no idea that what is the reason I keep receive error message from JSON exception error. Really appreciate somemore can help me.
Thanks
Be careful, PHP associative array are case sensitive
You are sending id:
nameValuePairs.add(new BasicNameValuePair("id",id));
which is not equal to ID
In addition to that mistake, you dont check the data in your php script, I rewrote it for you:
$data = array();
if(isset($_POST['id'], $_POST['Project_Id']){
$id=$_POST['id'];
$project_id=$_POST['Project_Id'];
$uname='root';
$pwd='';
$con = new PDO("mysql:host=192.168.0.111;dbname=wktask", $uname, $pwd);
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$stmt = $con->prepare('INSERT INTO task (`ID`, `Project_Id`) values(:id, :project_id)'))
$success = $stmt->execute(array(':id'=>$id, ':project_id'=>$project_id));
if($success){
$data['code'] = 1;
$data['msg'] = 'INSERT successful';
}else{
$data['code'] = 0;
$data['msg'] = 'INSERT Failed';
}
}else{
$data['code'] = 0;
$data['msg'] = 'values are not set';
}
echo(json_encode($data));

String Fails to pass between two activities

I'm passing two strings between two activities and for some strange reason, the strings aren't being passed. I've done all the correct protocols and nothing seems to work, despite tinkering around with the code for several hours, I'm sure it's an simple solution, but I have no clue, what's so ever.
1st Class:
public class LogIn extends Activity implements OnClickListener {
Button ok, back, exit;
TextView result;
EditText pword;
String password;
EditText uname;
String username;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Login button clicked
ok = (Button) findViewById(R.id.btn_login);
ok.setOnClickListener(this);
result = (TextView) findViewById(R.id.lbl_result);
}
//create bracket.
public void postLoginData() {
uname = (EditText) findViewById(R.id.txt_username);
uname.getText().toString();
pword = (EditText) findViewById(R.id.txt_password);
pword.getText().toString();
Bundle basket = new Bundle();
basket.putString("keypass", password);
basket.putString("keyuname", username);
Intent a = new Intent(LogIn.this, ChatService.class );
a.putExtras(basket);
startActivity(a);
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
/* login.php returns true if username and password is equal to saranga */
HttpPost httppost = new HttpPost("http://gta5news.com/login.php");
try {
// Add user name and password
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
Log.w("HttpPost(Login)", "Execute HTTP Post Request(Login 1)");
HttpResponse response = httpclient.execute(httppost);
String str = inputStreamToString(response.getEntity().getContent())
.toString();
Log.w("HttpPost", str);
if (str.toString().equalsIgnoreCase("true")) {
Log.w("HttpPost(Login2)", "TRUE");
result.setText("Login successful");
Intent login = new Intent(LogIn.this, ChatService.class);
startActivity(login);
}else {
Log.w("HttpPost(Login(3)", "FALSE");
result.setText(str);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private StringBuilder inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Return full string
return total;
}
public void onClick(View view) {
if (view == ok) {
postLoginData();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(pword.getWindowToken(), 0);
}
// Click end
}
// if statement
}
// class ends here
2nd class:
public class ChatService extends ListActivity {
/** Called when the activity is first created. */
BufferedReader in = null;
String data = null;
List headlines;
List links;
String GotPass;
String GotUname;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//get strings
Bundle gotData = getIntent().getExtras();
if(gotData !=null) {
GotPass = gotData.getString("keypass");
GotUname = gotData.getString("keyuname");
try {
//listview method
ContactsandIm();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
CheckLogin();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void CheckLogin() throws UnsupportedEncodingException {
// posts login data from "LogIn" class
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
/* login.php returns true if username and password is equal to saranga */
HttpPost httppost = new HttpPost("http://gta5news.com/login.php");
try {
// Add user name and password
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", GotUname));
nameValuePairs.add(new BasicNameValuePair("password", GotPass));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
Log.w("HttpPost(Login)", "Execute HTTP Post Request(ChatService 1)");
HttpResponse response = httpclient.execute(httppost);
String str = inputStreamToString(response.getEntity().getContent())
.toString();
Log.w("HttpPost", str);
if (str.toString().equalsIgnoreCase("true")) {
Log.w("HttpPost(ChatService 2)", "TRUE");
// make toast if str.equals("True")
Toast.makeText(getApplicationContext(), "Yayayaya, loged in", Toast.LENGTH_LONG );
}else {
Log.w("HttpPost(ChatService 3", "FALSE");
Toast.makeText(getApplicationContext(), "failed", Toast.LENGTH_LONG);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private StringBuilder inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Return full string
return total;
}
public void ContactsandIm() throws URISyntaxException,
ClientProtocolException, IOException {
headlines = new ArrayList();
// TODO Auto-generated method stub
BufferedReader in = null;
String data = null;
HttpClient get = new DefaultHttpClient();
URI website = new URI("http://www.gta5news.com/test.php");
HttpGet webget = new HttpGet();
webget.setURI(website);
HttpResponse response = get.execute(webget);
Log.w("HttpPost", "Execute HTTP Post Request");
in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent()));
StringBuffer sb = new StringBuffer("");
String l ="";
String nl ="";
while ((l =in.readLine()) !=null) {
sb.append(l + nl);
}
in.close();
data = sb.toString();
if(data.contains("null"));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
headlines.add(data);
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, headlines);
setListAdapter(adapter);
}
// end bracket for "ContactsandIm"
}
Try this way.
Intent a = new Intent(context, MyActivity.class);
a.putExtra("String1", "Hello World");
context.startActivity(a);
and
Bundle extras = getIntent().getExtras();
String s1 = extras.getString("String1");
You should add both 2 activity in Mainfest.xml file
Check have you register your activity in manifest file.

Categories