Log in and Signup page - android

I am creating sign up page for my app. I have 4 text fields in below code EditEmail, EditPass, EditRepass, EditMobile. I already made login page, now I need to make some changes in my login code to make sign up page work. But I think I made few mistakes. In login I have a check box, but in this code it is not required. I do not know how to tackle with checbox code. I want to send the above 4 fields to my remote server and check if "email id" is not used before then user get registered. How should I make the following code perfect.
public class SignUpActivity extends Activity
{
EditText editEmail, editPass, editRepass, editMobile;
Button submit,exit;
String name = "", pass = "", repass = "", mobile = "";
SharedPreferences app_preferences;
Intent i;
CheckBox check;
byte[] data;
HttpPost httppost;
HttpResponse response;
HttpClient httpclient;
StringBuffer buffer;
InputStream inputStream;
List<NameValuePair> nameValuePairs;
#Override
public void onCreate (Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.signup);
submit = (Button) findViewById(R.id.submit);
exit = (Button) findViewById(R.id.exit);
editEmail=(EditText)findViewById(R.id.editEmail);
editPass=(EditText)findViewById(R.id.editPass);
editRepass=(EditText)findViewById(R.id.editRepass);
editMobile=(EditText)findViewById(R.id.editMobile);
app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
check = (CheckBox) findViewById(R.id.check);
String Str_user = app_preferences.getString("username", "0");
String Str_pass = app_preferences.getString("password", "0");
String Str_repass = app_preferences.getString("repassword", "0");
String Str_mobile = app_preferences.getString("mobile", "0");
String Str_check = app_preferences.getString("checked", "no");
if (Str_check.equals("yes")) {
editTextId.setText(Str_user);
editTextP.setText(Str_pass);
check.setChecked(true);
}
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
name = editEmail.getText().toString();
pass = editPass.getText().toString();
repass = editRepass.getText().toString();
mobile = editMobile.getText().toString();
String Str_check2 = app_preferences.getString("checked", "no");
if (Str_check2.equals("yes")) {
SharedPreferences.Editor editor = app_preferences.edit();
editor.putString("username", name);
editor.putString("password", pass);
editor.putString("repassword", repass);
editor.putString("umobile", mobile);
editor.commit();
}
if (name.equals("") || pass.equals("") || repass.equals("") || mobile.equals("") ) {
Toast.makeText(SignUpActivity.this, "Blank Field..Please Enter", Toast.LENGTH_SHORT).show();
} else {
}
}
});
exit.setOnClickListener(new View.OnClickListener ()
{
public void onClick(View v)
{
finish();
}
});
}
public void Move_to_next1()
{
startActivity(new Intent(SignUpActivity.this, SplashActivity.class));
finish();
}
#SuppressLint("NewApi")
private class LoginTask extends AsyncTask <Void, Void, String>
{
#SuppressLint("NewApi")
#Override
protected void onPreExecute()
{
super.onPreExecute();
// Show progress dialog here
}
#Override
protected String doInBackground(Void... arg0) {
try {
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://abc.com/login1.php");
// Add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("UserEmail", name.trim()));
nameValuePairs.add(new BasicNameValuePair("Password", pass.trim()));
nameValuePairs.add(new BasicNameValuePair("RePassword", repass.trim()));
nameValuePairs.add(new BasicNameValuePair("Mobile", mobile.trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
response = httpclient.execute(httppost);
inputStream = response.getEntity().getContent();
data = new byte[256];
buffer = new StringBuffer();
int len = 0;
while (-1 != (len = inputStream.read(data))) {
buffer.append(new String(data, 0, len));
}
inputStream.close();
return buffer.toString();
}
catch (Exception e)
{
e.printStackTrace();
}
return "";
}
#SuppressLint("NewApi")
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// Hide progress dialog here
if (buffer.charAt(0) == 'Y')
{
Toast.makeText(SignUpActivity.this, "Succesfully Registered", Toast.LENGTH_SHORT).show();
Move_to_next1();
}
else
{
Toast.makeText(SignUpActivity.this, " E-Mail Already Registered", Toast.LENGTH_SHORT).show();
}
}
}
}

Related

SharedPreferences variable is only received and can be shown on a second execution

I searched all forums and solutions but none did the trick. I have an app that scans some text and receive the scan text and show it. This is the file where I get the scan results:
#Override
public void extractData(RomaniaIdFrontRecognizer.Result result) {
super.extractData(result);
savePreferences("selected", result.getLastName());
add(R.string.PPLastName, result.getLastName());
add(R.string.PPFirstName, result.getFirstName());
add(R.string.PPIdentityCardNumber, result.getCardNumber());
add(R.string.PPSeries, result.getIdSeries());
add(R.string.PPCNP, result.getCnp());
add(R.string.PPNationality, result.getNonMRZNationality());
add(R.string.PPPlaceOfBirth, result.getPlaceOfBirth());
add(R.string.PPAddress, result.getAddress());
add(R.string.PPIssuingAuthority, result.getIssuedBy());
add(R.string.PPSex, result.getNonMRZSex());
add(R.string.PPValidFrom, result.getValidFrom());
add(R.string.PPValidUntil, result.getValidUntil());
}
private void savePreferences(String key, String value){
SharedPreferences sharedPreferences = mContext.getSharedPreferences("weightSetting", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
This part is being executed because if I put a toast, the message shows.
And this is the file where I would want to receive the variable sent with sharedpreferences:
public class ResultActivity extends FragmentActivity implements
ResultFragment.IResultFragmentActivity,
FieldByFieldResultFragment.IFieldByFieldResultFragmentActivity {
String a;
String TempName, TempEmail ;
String e;
Bitmap bitmap;
ByteArrayOutputStream baos;
byte[] imageInByte;
private LayoutInflater mInflater;
Toast toast;
LoginDataBaseAdapter loginDataBaseAdapter;
EditText nume;
EditText prenume;
EditText nr;
EditText serie;
EditText cnp;
EditText nationalitate;
EditText loc;
EditText adresa;
EditText emis;
EditText sex;
EditText start;
EditText stop;
String usern;
public static final String EXTRAS_RESULT_TYPE = "EXTRAS_RESULT_TYPE";
public enum ResultType {
RECOGNIZER_BUNDLE,
FIELD_BY_FIELD_BUNDLE
}
protected ViewPager mPager;
protected RecognizerBundle mRecognizerBundle;
protected FieldByFieldBundle mFieldByFieldBundle;
protected ResultType mResultType;
private ArrayList<Recognizer> mRecognizersWithResult;
#SuppressLint("InlinedApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setActivityContentView();
// loginDataBaseAdapter=new LoginDataBaseAdapter(getApplicationContext());
// loginDataBaseAdapter=loginDataBaseAdapter.open();
// String aa=loginDataBaseAdapter.getMagazin();
String s = loadPreferences("selected");
Toast.makeText(getApplicationContext(), s,Toast.LENGTH_LONG).show();
Intent intent = getIntent();
mResultType = (ResultType) intent.getSerializableExtra(EXTRAS_RESULT_TYPE);
mRecognizerBundle = new RecognizerBundle();
mFieldByFieldBundle = new FieldByFieldBundle();
if (mResultType == null) {
if (mRecognizerBundle.existsInIntent(intent)) {
mResultType = ResultType.RECOGNIZER_BUNDLE;
} else if (mFieldByFieldBundle.existsInIntent(intent)) {
mResultType = ResultType.FIELD_BY_FIELD_BUNDLE;
}
}
if (mResultType == null) {
throw new IllegalStateException("Results must be passed to ResultActivity!");
}
mPager = findViewById(R.id.resultPager);
switch (mResultType) {
case RECOGNIZER_BUNDLE:
mRecognizersWithResult = new ArrayList<>();
mRecognizerBundle.loadFromIntent(intent);
for ( Recognizer< Recognizer, Recognizer.Result > r : mRecognizerBundle.getRecognizers() ) {
if ( r.getResult().getResultState() != Recognizer.Result.State.Empty ) {
mRecognizersWithResult.add( r );
// String text = mRecognizersWithResult.get(0).toString();
// Toast.makeText(getApplicationContext(), text,Toast.LENGTH_LONG).show();
}
}
mPager.setAdapter(new RecognizerListFragmentAdapter(getSupportFragmentManager()));
break;
case FIELD_BY_FIELD_BUNDLE:
// mFieldByFieldBundle.loadFromIntent(intent);
// mPager.setAdapter(new FieldByFieldBundleFragmentAdapter(getSupportFragmentManager()));
// break;
}
TabPageIndicator indicator = findViewById(R.id.resultIndicator);
indicator.setViewPager(mPager);
indicator.setClipChildren(false);
}
#Override
protected void onResume() {
super.onResume();
// clear saved state to be sure that data is cleared from cache and from file when
// intent optimisation is used
mRecognizerBundle.clearSavedState();
mFieldByFieldBundle.clearSavedState();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mResultType == ResultType.RECOGNIZER_BUNDLE) {
mRecognizerBundle.saveState();
} else if (mResultType == ResultType.FIELD_BY_FIELD_BUNDLE) {
mFieldByFieldBundle.saveState();
}
}
public void setActivityContentView() {
setContentView(R.layout.result_menu);
}
private String loadPreferences(String key){
SharedPreferences sharedPreferences =getApplicationContext().getSharedPreferences("weightSetting", MODE_PRIVATE);
String load = sharedPreferences.getString(key, "");
return load;
}
#Override
public Recognizer< Recognizer, Recognizer.Result > getRecognizerAtPosition(int resultPosition) {
if (resultPosition < 0 || resultPosition >= mRecognizersWithResult.size()) {
throw new IllegalStateException("Recognizer with non empty result on requested position"
+ " does not exist. Possible cause is that recognizer bundle state has been lost"
+ " in intent transactions.");
}
//noinspection unchecked
return mRecognizersWithResult.get(resultPosition);
}
#Override
public FieldByFieldBundle getFieldByFieldBundle() {
return mFieldByFieldBundle;
}
private class RecognizerListFragmentAdapter extends FragmentPagerAdapter {
RecognizerListFragmentAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return ResultFragment.newInstance(position);
}
#Override
public int getCount() {
return mRecognizersWithResult.size();
}
#Override
public CharSequence getPageTitle(int position) {
return ResultUtils.getRecognizerSimpleName(mRecognizersWithResult.get(position));
}
}
private class FieldByFieldBundleFragmentAdapter extends FragmentPagerAdapter {
FieldByFieldBundleFragmentAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return FieldByFieldResultFragment.newInstance();
}
#Override
public int getCount() {
return 1;
}
#Override
public CharSequence getPageTitle(int position) {
return ResultActivity.this.getString(R.string.title_field_by_field_results);
}
}
public void footerButtonClickHandler(View view) {
// String sessionId= getIntent().getStringExtra("test");
// Toast.makeText(getApplicationContext(), "da", Toast.LENGTH_LONG).show();
// new RegisterAsyntaskNew().execute();
ImageView img=(ImageView) findViewById(R.id.resultValueee);
// img.buildDrawingCache();
// Bitmap bitmap = img.getDrawingCache();
BitmapDrawable drawable = (BitmapDrawable) img.getDrawable();
Bitmap bitmap = drawable.getBitmap();
baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
imageInByte = baos.toByteArray();
// RomanianIDFrontSideRecognitionResultExtractor myActivity2 = new RomanianIDFrontSideRecognitionResultExtractor();
// myActivity2.InsertData();
Img(imageInByte,e);
// InsertData(nume.getText().toString(), prenume.getText().toString(), nr.getText().toString(), serie.getText().toString(),cnp.getText().toString(),nationalitate.getText().toString(), loc.getText().toString(),adresa.getText().toString(),emis.getText().toString(),sex.getText().toString(),start.getText().toString(),stop.getText().toString(),usern);
finish();
}
public void InsertData(final String nume, final String prenume, final String nr, final String serie, final String cnp, final String nationalitate
, final String locn, final String adresa, final String emis, final String sex, final String start, final String sfarsit,final String username){
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String name = nume ;
String pren = prenume ;
String nr1 = nr;
String serie1 = serie ;
String cnp1 = cnp ;
String nat = nationalitate ;
String locn1 = locn ;
String adresa1 = adresa ;
String emis1 = emis ;
String sex1 = sex ;
String start1 = start ;
String sfarsit1 = sfarsit ;
String user1 = username ;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name", name));
nameValuePairs.add(new BasicNameValuePair("email", pren));
nameValuePairs.add(new BasicNameValuePair("nr", nr1));
nameValuePairs.add(new BasicNameValuePair("serie", serie1));
nameValuePairs.add(new BasicNameValuePair("cnp", cnp1));
nameValuePairs.add(new BasicNameValuePair("nat", nat));
nameValuePairs.add(new BasicNameValuePair("locn", locn1));
nameValuePairs.add(new BasicNameValuePair("adresa", adresa1));
nameValuePairs.add(new BasicNameValuePair("emis", emis1));
nameValuePairs.add(new BasicNameValuePair("sex", sex1));
nameValuePairs.add(new BasicNameValuePair("start", start1));
nameValuePairs.add(new BasicNameValuePair("sfarsit", sfarsit1));
nameValuePairs.add(new BasicNameValuePair("username", user1));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("url");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
a = EntityUtils.toString(httpResponse.getEntity());
// return EntityUtils.toString(httpEntity).trim();
ResultActivity.this.runOnUiThread(new Runnable() {
public void run() {
// Toast.makeText(ResultActivity.this, a, Toast.LENGTH_LONG).show();
toast = Toast.makeText(ResultActivity.this, a, Toast.LENGTH_SHORT);
TextView v = (TextView) toast.getView().findViewById(android.R.id.message);
v.setTextColor(Color.parseColor("#66ff33"));
int toastDuration = 5000;
CountDownTimer countDownTimer;
countDownTimer = new CountDownTimer(toastDuration, 1000) {
public void onTick(long millisUntilFinished) {
toast.show();
}
public void onFinish() {
toast.cancel();
}
};
toast.show();
countDownTimer.start();
}
});
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return "Data Inserted Successfully";
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(nume, prenume,nr,serie,cnp,nationalitate,locn,adresa,emis,sex,start,sfarsit,username);
}
public void Img(final byte[] data,final String cnpimg){
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String cnp1 = cnpimg ;
Bitmap bitmapOrg = BitmapFactory.decodeByteArray(data, 0, data.length);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte[] ba = bao.toByteArray();
String ba1 = Base64.encodeBytes(ba);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("image", ba1));
nameValuePairs.add(new BasicNameValuePair("cnp", cnp1));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://promotii.grupsapte.ro/php/scanid/img.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
// a = EntityUtils.toString(httpResponse.getEntity());
// return EntityUtils.toString(httpEntity).trim();
// ResultActivity.this.runOnUiThread(new Runnable() {
// public void run() {
// Toast.makeText(ResultActivity.this, a, Toast.LENGTH_LONG).show();
// }
// });
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return "Data Inserted Successfully";
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute();
}
}
The send-receive variable with shared preferences worked but now, i don't know the cause, first time I get a null variable and if I try it again then I receive what I scan first. So, the variable is shown only the second time with the value scan for the first time. Even if I try to put a simple text and send it, it will show only the second time I make the action. But I repeat, the file is getting executed because if I put a toast, it will show. I think that the receiving of the shared preferences variable is done first and then the code from the first file is being executed. I tried to put the code in oncreate, onresume but nothing did the trick. Any help would be much appreciated.
The solution for me was to put a delay of 1 second for the process of receiving thorugh shared preferences. See below:
#Override
protected void onResume() {
super.onResume();
// clear saved state to be sure that data is cleared from cache and from file when
// intent optimisation is used
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
// Your logic here...
// When you need to modify a UI element, do so on the UI thread.
// 'getActivity()' is required as this is being ran from a Fragment.
ResultActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// This code will always run on the UI thread, therefore is safe to modify UI elements.
String a = loadPreferences("nume");
String b= loadPreferences("prenume");
String c= loadPreferences("nr");
String d= loadPreferences("serie");
e= loadPreferences("cnp");
String f= loadPreferences("nationalitate");
String g= loadPreferences("locn");
String h= loadPreferences("adresa");
String i= loadPreferences("emis");
String j= loadPreferences("sex");
String k= loadPreferences("start");
String l= loadPreferences("sfarsit");
usern= "";
String s = Normalizer.normalize(f, Normalizer.Form.NFD);
String bla = s.replaceAll("[\\p{InCombiningDiacriticalMarks}]", "");
String t = Normalizer.normalize(h, Normalizer.Form.NFD);
String bla1 = t.replaceAll("[\\p{InCombiningDiacriticalMarks}]", "");
String a1 = Normalizer.normalize(a, Normalizer.Form.NFD);
String bla2 = a1.replaceAll("[\\p{InCombiningDiacriticalMarks}]", "");
String b1 = Normalizer.normalize(b, Normalizer.Form.NFD);
String bla3 = b1.replaceAll("[\\p{InCombiningDiacriticalMarks}]", "");
String g1 = Normalizer.normalize(g, Normalizer.Form.NFD);
String bla4 = g1.replaceAll("[\\p{InCombiningDiacriticalMarks}]", "");
nume = (EditText) findViewById(R.id.nume);
nume.setText(bla2);
prenume = (EditText) findViewById(R.id.prenume);
prenume.setText(bla3);
nr = (EditText) findViewById(R.id.nrserie);
nr.setText(c);
serie = (EditText) findViewById(R.id.serie);
serie.setText(d);
cnp = (EditText) findViewById(R.id.cnp);
cnp.setText(e);
nationalitate = (EditText) findViewById(R.id.nationalitate);
nationalitate.setText(bla);
loc = (EditText) findViewById(R.id.loc);
loc.setText(bla4);
adresa = (EditText) findViewById(R.id.adresa);
adresa.setText(bla1);
emis = (EditText) findViewById(R.id.emis);
emis.setText(i);
sex = (EditText) findViewById(R.id.sexx);
sex.setText(j);
start = (EditText) findViewById(R.id.start);
start.setText(k);
stop = (EditText) findViewById(R.id.stop);
stop.setText(l);
// String s = loadPreferences("selected");
// Toast.makeText(getApplicationContext(), a,Toast.LENGTH_LONG).show();
}
});
}
}, 1000); // End of your timer code.
mRecognizerBundle.clearSavedState();
mFieldByFieldBundle.clearSavedState();
}

Response:wrong. [User registration via android app using http post not working]

I was able to successfully make login work. Now, I am stuck up with registration. Response is wrong.
public class Register extends Activity implements OnClickListener{
private String mTitle = "Write.My.Action";
private static final String LOGTAG = "tag";
public EditText fullname, email, password;
private Button register;
private ProgressDialog mDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
getActionBar().setTitle(mTitle);
fullname = (EditText) findViewById(R.id.fullname);
email = (EditText) findViewById(R.id.editText2);
password = (EditText) findViewById(R.id.editText1);
register = (Button) findViewById(R.id.button1);
register.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
mDialog = new ProgressDialog(Register.this);
mDialog.setMessage("Attempting to Register...");
mDialog.setIndeterminate(false);
mDialog.setCancelable(false);
mDialog.show();
new Thread(new Runnable() {
#Override
public void run() {
register();
}
}).start();
}
}
void register() {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("myurl");
System.out.println("httpPost is: " + httpPost);
String fullname_input = fullname.getText().toString().trim();
String email_input = email.getText().toString().trim();
String password_input = password.getText().toString().trim();
//adding data into list view so we can make post over the server
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair("fullname", fullname_input));
nameValuePair.add(new BasicNameValuePair("email", email_input));
nameValuePair.add(new BasicNameValuePair("password", password_input));
System.out.println("namevaluepair is: " + nameValuePair);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
//execute http post resquest
HttpResponse httpResponse = httpClient.execute(httpPost);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpClient.execute(httpPost, responseHandler);
System.out.println("Response is: " + response);
runOnUiThread(new Runnable() {
#Override
public void run() {
mDialog.dismiss();
}
});
if(response.equalsIgnoreCase("Signed Up")){
runOnUiThread(new Runnable() {
#Override
public void run() {
startActivity(new Intent(Register.this, Registration_Success.class));
}
});
}else {
showAlert();
}
} catch (Exception e) {
mDialog.dismiss();
Log.i(LOGTAG, "Exception found"+ e.getMessage());
}
}
public void showAlert(){
Register.this.runOnUiThread(new Runnable() {
#Override
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(Register.this);
builder.setTitle("Registration Error");
builder.setMessage("Please, try registration again!")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
}
Please Note: Every activities are registered in Manifest, INTERNET permission also included.
php file:
include "dbconnection.php";
$fullname = $_POST['fullname'];
$email = $_POST['email'];
$password = $_POST['password'];
$insert_data = "INSERT INTO register
Values ('', '$fullname', '$email', '$password')";
$insert_result = mysql_query($insert_data);
//echo "Signed Up";
if($insert_result){
echo "Signed Up";
}
else{
echo "wrong!";
}
I don't understand why it keeps on saying Response is : Wrong. Tired of spending almost a day .. I am here seeking help.
Excuse me if my questions seems naive.
Thank you in advance.
try below code:-
HttpResponse httpResponse = httpClient.execute(httpPost);
if (httpResponse != null)
{
InputStream in = httpResponse.getEntity().getContent();
result = ConvertStreamToString.convertStreamToString(in);
// System.out.println("result =>" + result);
}
convertStreamToString method
public String convertStreamToString(InputStream is)
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try
{
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
is.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
return sb.toString();
}
do not under stand :-
HttpResponse httpResponse = httpClient.execute(httpPost); // getting response from server
// where you use this response and why using below line or whats the benefit of below line
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpClient.execute(httpPost, responseHandler);
Follow that tutorial very usefull, and clear how to work on json webservices with android.
How to connect Android with PHP, MySQL
Try this code using AsyncTask
public class Register extends Activity implements OnClickListener{
private String mTitle = "Write.My.Action";
private static final String LOGTAG = "tag";
public EditText fullname, email, password;
private Button register;
private ProgressDialog mDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
getActionBar().setTitle(mTitle);
fullname = (EditText) findViewById(R.id.fullname);
email = (EditText) findViewById(R.id.editText2);
password = (EditText) findViewById(R.id.editText1);
register = (Button) findViewById(R.id.button1);
register.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
mDialog = new ProgressDialog(Register.this);
mDialog.setMessage("Attempting to Register...");
mDialog.setIndeterminate(false);
mDialog.setCancelable(false);
mDialog.show();
new RegisterUser().execute();
}
}
public class RegisterUser extends AsyncTask<Void, Void, String>
{
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("myurl");
System.out.println("httpPost is: " + httpPost);
String fullname_input = fullname.getText().toString().trim();
String email_input = email.getText().toString().trim();
String password_input = password.getText().toString().trim();
//adding data into list view so we can make post over the server
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair("fullname", fullname_input));
nameValuePair.add(new BasicNameValuePair("email", email_input));
nameValuePair.add(new BasicNameValuePair("password", password_input));
System.out.println("namevaluepair is: " + nameValuePair);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
//execute http post resquest
HttpResponse httpResponse = httpClient.execute(httpPost);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpClient.execute(httpPost, responseHandler);
System.out.println("Response is: " + response);
return response;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(response.equalsIgnoreCase("Signed Up")){
runOnUiThread(new Runnable() {
#Override
public void run() {
startActivity(new Intent(Register.this, Registration_Success.class));
}
});
}else {
showAlert();
}
}
}
public void showAlert(){
Register.this.runOnUiThread(new Runnable() {
#Override
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(Register.this);
builder.setTitle("Registration Error");
builder.setMessage("Please, try registration again!")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
}
Hope this helps you!!!
If its not working please let me know i will try to help more...
Try using Volley if not. It's faster than the ussual HTTP connection classes.
Example:
RequestQueue queue = Volley.newRequestQueue(this);
String url = "url";
JSONObject juser = new JSONObject();
try {
juser.put("locationId", locID);
juser.put("email", email_input);
juser.put("password", password_input);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST, url, juser, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// TODO Auto-generated method stub
txtDisplay.setText("Response => "+response.toString());
findViewById(R.id.progressBar1).setVisibility(View.GONE);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
}
});
queue.add(jsObjRequest);
Like #Andrew T suggested , I am posting my solution.
The mysql_error()helped me debug the issue. mysql_error() displayed in the Logcat that "register table is not found" .. but the table name is registers. I was missing "s" at the end.
$fullname = $_POST['fullname'];
$email = $_POST['email'];
$password = $_POST['password'];
$insert_data = "INSERT INTO registers(id, fullname, email, password)
Values ('','$fullname', '$email', '$password')";
$insert_result = mysql_query($insert_data) or die(mysql_error());
//echo "Signed Up";
if($insert_result){
echo "Signed Up";
}
else{
echo "wrong!";
}
Everything worked perfect after that. Again, thank you all for your time and solutions. Everyone's suggestions are great, but I can not accept any answer at this point.. sorry:(

login page with httpget and asynctask in android

Hi I'm new to android and have task to create a login page that will connect with server and check user exist using http Get and AsyncTask and PHP API for this is ready. i went through few tutorials on AsyncTask and i understood but i m not sure how to work with http Get and AsyncTask. can anyone please help how to link both and create login page.
P.S: i have two EditText to accept username and password and two Buttons one for login and other for register and have corresponding DB as well.
This is sample code-
public class LoginActivity extends Activity
{
Intent i;
Button signin, signup;
String name = "", pass = "";
byte[] data;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
InputStream inputStream;
SharedPreferences app_preferences, pref;
List<NameValuePair> nameValuePairs;
EditText editTextId, editTextP;
SharedPreferences.Editor editor;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
signin = (Button) findViewById(R.id.signin);
signup = (Button) findViewById(R.id.signup);
editTextId = (EditText) findViewById(R.id.editTextId);
editTextP = (EditText) findViewById(R.id.editTextP);
app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
String Str_user = app_preferences.getString("username", "0");
String Str_pass = app_preferences.getString("password", "0");
String Str_check = app_preferences.getString("checked", "no");
if (Str_check.equals("yes"))
{
editTextId.setText(Str_user);
editTextP.setText(Str_pass);
}
signin.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
signin.setEnabled(false);
signup.setEnabled(false);
name = editTextId.getText().toString();
pass = editTextP.getText().toString();
String Str_check2 = app_preferences.getString("checked", "no");
if (Str_check2.equals("yes")) {
SharedPreferences.Editor editor = app_preferences.edit();
editor.putString("username", name);
editor.putString("password", pass);
editor.commit();
}
if (name.equals("") || pass.equals(""))
{
Toast.makeText(LoginActivity.this, "Blank Field..Please Enter", Toast.LENGTH_SHORT).show();
signin.setEnabled(true);
signup.setEnabled(true);
}
else
{
String emailPattern = "[a-zA-Z0-9._-]+#[a-z]+\\.+[a-z]+";
if(name.matches(emailPattern))
new LoginTask().execute();
signin.setEnabled(false);
signup.setEnabled(false);
}
}
});
signup.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
Move_next();
}
});
}
public void Move_to_next()
{
final Handler handle = new Handler();
Runnable delay = new Runnable() {
public void run() {
startActivity(new Intent(LoginActivity.this, SplashActivity.class));
finish();
}
};
handle.postDelayed(delay,2000);
}
public void Move_next()
{
startActivity(new Intent(LoginActivity.this, SignUpActivity.class));
finish();
}
#SuppressLint("NewApi")
private class LoginTask extends AsyncTask <Void, Void, String>
{
#SuppressLint("NewApi")
#Override
protected void onPreExecute()
{
super.onPreExecute();
// Show progress dialog here
}
#Override
protected String doInBackground(Void... arg0) {
try {
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://website.com/yourpagename.php");
// Add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("UserEmail", name.trim()));
nameValuePairs.add(new BasicNameValuePair("Password", pass.trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
response = httpclient.execute(httppost);
inputStream = response.getEntity().getContent();
data = new byte[256];
buffer = new StringBuffer();
int len = 0;
while (-1 != (len = inputStream.read(data))) {
buffer.append(new String(data, 0, len));
}
inputStream.close();
return buffer.toString();
}
catch (Exception e)
{
e.printStackTrace();
}
return "";
}
#SuppressLint("NewApi")
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// Hide progress dialog here
if (buffer.charAt(0) == 'Y')
{
Toast.makeText(LoginActivity.this, "login successfull", Toast.LENGTH_SHORT).show();
Move_to_next();
}
else
{
Toast.makeText(LoginActivity.this, "Invalid Username or password", Toast.LENGTH_SHORT).show();
signin.setEnabled(true);
signup.setEnabled(true);
}
}
}
}

Android - android.os.NetworkOnMainThreadException when acess Http client [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
android.os.NetworkOnMainThreadException
When I run the my android application, I got android.os.NetworkOnMainThreadException, what is the reason for that.how do I fix It.this is my code
public class Login extends Activity {
private Button btnLogin;
private EditText txtusername;
private EditText txtPassword;
public String username;
public String password;
public boolean doLogin = false;
Intent intent;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.login);
btnLogin = (Button) findViewById(R.id.btnLogin);
txtusername = (EditText) findViewById(R.id.txtuserName);
txtPassword = (EditText) findViewById(R.id.txtPassword);
btnLogin.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
username = txtusername.getText().toString();
password = txtPassword.getText().toString();
if (username.equals("") || password.equals("")) {
AlertDialog alert = new AlertDialog.Builder(Login.this)
.create();
alert.setMessage("Username or Password can not be Empty");
alert.setButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
}
});
alert.setIcon(R.drawable.loginlogo);
alert.show();
}
else {
HttpAsync httpasync = new HttpAsync();
httpasync.execute(new String[] { "http://www.diskonbanget.com/bni/login/login.php" });
}
}
});
}
private class HttpAsync extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String str = null;
try {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://www.diskonbanget.com/bni/login/login.php");
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
HttpResponse response = httpclient.execute(httppost);
str = inputStreamToString(response.getEntity().getContent())
.toString();
} catch (Exception e) {
return str;
}
return str;
}
#Override
protected void onPostExecute(String result) {
String str = result;
if (str.toString().equalsIgnoreCase("false")) {
AlertDialog alert = new AlertDialog.Builder(Login.this)
.create();
alert.setMessage("Please enter valid username & Password");
alert.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alert.setIcon(R.drawable.loginlogo);
alert.show();
}
else if (str.toString().equalsIgnoreCase("null")) {
AlertDialog alert = new AlertDialog.Builder(Login.this)
.create();
alert.setMessage("Can not Connect to the server.please make sure your internet is Switch on ");
alert.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alert.setIcon(R.drawable.loginlogo);
alert.show();
}
else {
intent = new Intent(Login.this, MainMenu.class);
intent.putExtra("photo", str);
intent.putExtra("username", str);
getApplicationContext().startActivity(intent);
}
}
}
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);
}
return total;
} catch (Exception e) {
return null;
}
}
please someone help me.android version3.2, try to run using XOOM2 emulator
The reason is that your login method makes an http connection in the ui thread, you should do it in a separate thread or use an AsynchTask..
You can pass the context to the task, and then:
protected void onPostExecute(Void result) {
Intent showContent = new Intent(context, yourActivity.class);
context.startActivity(showContent);
}
I dont advise it though but you can use this for test. Refer to #imran khan for good practice.
Add this in your onCreate() method to bypass the checking.
if( Build.VERSION.SDK_INT >= 9){
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}

StartActivity() red highlighted

Basically I want to have a button to start a new activity after login.
I found that I was not able to call the StartActivity() as what I did before in the login page.Please guide
This is the login page where I used StartActivity(this,sth.class)sucessfully
public class Login extends Activity
{
/** Called when the activity is first created. */
Button login;
String name="",pass="";
EditText username,password;
TextView tv;
byte[] data;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
InputStream inputStream;
SharedPreferences app_preferences ;
List<NameValuePair> nameValuePairs;
CheckBox check;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
login = (Button) findViewById(R.id.login);
check = (CheckBox) findViewById(R.id.check);
String Str_user = app_preferences.getString("username","0" );
String Str_pass = app_preferences.getString("password", "0");
String Str_check = app_preferences.getString("checked", "no");
if(Str_check.equals("yes"))
{
username.setText(Str_user);
password.setText(Str_pass);
check.setChecked(true);
}
login.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
name = username.getText().toString();
pass = password.getText().toString();
String Str_check2 = app_preferences.getString("checked", "no");
if(Str_check2.equals("yes"))
{
SharedPreferences.Editor editor = app_preferences.edit();
editor.putString("username", name);
editor.putString("password", pass);
editor.commit();
}
if(name.equals("") || pass.equals(""))
{
Toast.makeText(Login.this, "Blank Field..Please Enter", Toast.LENGTH_LONG).show();
}
else
{
try {
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://fyptest.comyr.com/main.php");
// Add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("UserEmail", name.trim()));
nameValuePairs.add(new BasicNameValuePair("Password", pass.trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
response = httpclient.execute(httppost);
inputStream = response.getEntity().getContent();
data = new byte[256];
buffer = new StringBuffer();
int len = 0;
while (-1 != (len = inputStream.read(data)) )
{
buffer.append(new String(data, 0, len));
}
inputStream.close();
}
catch (Exception e)
{
Toast.makeText(Login.this, "error"+e.toString(), Toast.LENGTH_LONG).show();
}
if(buffer.charAt(0)=='Y')
{
Toast.makeText(Login.this, "login successfull", Toast.LENGTH_LONG).show();
Move_to_next();
}
else
{
Toast.makeText(Login.this, "Invalid Username or password", Toast.LENGTH_LONG).show();
}
}
}
});
check.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
// Perform action on clicks, depending on whether it's now checked
SharedPreferences.Editor editor = app_preferences.edit();
if (((CheckBox) v).isChecked())
{
editor.putString("checked", "yes");
editor.commit();
}
else
{
editor.putString("checked", "no");
editor.commit();
}
}
});
}
public void Move_to_next()
{
//may perform checking based on ID
startActivity(new Intent(this, MainMenu.class));
}
But this, my startActivity is being underlined in red
public class MainMenu extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main_menu);
Button new_folder = (Button)findViewById(R.id.new_folder);
new_folder.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
// show another class
startActivity(new Intent(this,Folder_Details.class));
}
});
}
}
It shows "The constructor Intent(new View.OnClickListener(){}, Class) is undefined" and "Remove arguments to match Intent()" options
I have included the <Activity></Activity> in Manifest. And the code showed above, imports are cut off
Yes this is because, you are trying to use "this" with refernce to your button instead of your activity. You have to replace it like this,
Instead of startActivity(new Intent(this, Folder_Details.class));
do this,
startActivity(new Intent(MainMenu.this, Folder_Details.class));
Modify it as
startActivity(new Intent(MainMenu.this,Folder_Details.class));
You are using a View.OnClickListener instead of a Context instance.
startActivity(new Intent(MainMenu.this,Folder_Details.class));

Categories

Resources