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();
}
I have a problem i need the token to transfer it to my SessionManagement class to compare it with the saved token , but in my onCreate it's always null ,i need a workaround to make my token not null in oncreate
please help.
here is my code
private static final String LOGIN_URL = "http://baymd.myterranet.com/api/auth";
private static final String TAG_SUCCESS = "code";
private static final String TAG_MESSAGE = "message";
private static final String TAG_DATA = "data";
private static final String TAG_TOKEN = "access_token";
JSONParser jsonParser = new JSONParser();
private EditText user, pass;
private Button mSubmit;
private ProgressDialog pDialog;
private String token, none,SavedToken;
SesionManagement session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
session=new SesionManagement(getApplicationContext());
HashMap<String, String> tokens = session.getUserDetails();
SavedToken = tokens.get(session.KEY_NAME);
if(token==null) {//This line
Log.d("TOKEN ====== ", "NULLL");
}
session.checkLogin(token, SavedToken);
user = (EditText) findViewById(R.id.inputEmail);
pass = (EditText) findViewById(R.id.inputPass);
mSubmit = (Button) findViewById(R.id.loginBtn);
mSubmit.setOnClickListener(this);
}
#Override
public void onClick(View v) {
new AttemptLogin().execute();
}
class AttemptLogin extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Attempting login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
int success;
String username = user.getText().toString();
String password = pass.getText().toString();
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", username));
params.add(new BasicNameValuePair("password", password));
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params, none);
success = json.getInt(TAG_SUCCESS);
if (success == 200) {
JSONObject c = json.getJSONObject(TAG_DATA);
token = c.getString(TAG_TOKEN);//The token wich is null in oncreate
Intent i = new Intent(Login.this, NavDraver.class);
i.putExtra("cjson", c.toString());
finish();
startActivity(i);
return json.getString(TAG_MESSAGE);
} else {
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
json.getString(TAG_MESSAGE);
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
session.createLoginSession(token);
Log.d("SAVED TOKEN",SavedToken);
pDialog.dismiss();
}
}
}
Try this:
token = c.optString(TAG_TOKEN, yourDefaultValueHere);
if(token == null){
token = ""; // or whatever you want to init here
}
Hope it helps.
i am trying to make get a json value to display on another class but it is returning a null value and i am trying to save it using sharedpreferences and it is not working . i want to get editor.putString("username", username); display the username on the next class which is menu . and it is displaying anon
public class MainActivity extends Activity {
Button login,signin,reg,forr;
private EditText user,pass;
private ProgressDialog pDialog;
int flag=0;
JSONParser jsonParser = new JSONParser();
private static String LOGIN_URL = "http://10.0.2.2/wordtinss/login.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
private static final String DAIRY = "dairy";
public static final String PREFS_NAME = "LoginPrefs";
#Override
protected void onCreate(Bundle savedInstanceState) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads().detectDiskWrites().detectNetwork()
.penaltyLog().build());
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
login=(Button)findViewById(R.id.login);
user=(EditText)findViewById(R.id.username);
pass=(EditText)findViewById(R.id.password);
reg=(Button) findViewById(R.id.reg);
forr=(Button) findViewById(R.id.forg);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
if (settings.getString("logged", "").toString().equals("logged")) {
Intent intent = new Intent(MainActivity.this, Menu.class);
startActivity(intent);
}
reg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, Register.class);
finish();
startActivity(i);
}
//Close code that check online details
});
//Close log in
forr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, Forget.class);
finish();
startActivity(i);
}
//Close code that check online details
});
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Check all fields
if(user.length()<1 || pass.length()<1)
{
Toast.makeText(MainActivity.this,"Please Enter both username and password", Toast.LENGTH_LONG).show();
return;
}
//check connectivity
if(!isOnline(MainActivity.this))
{
Toast.makeText(MainActivity.this,"No network connection", Toast.LENGTH_LONG).show();
return;
}
//from login.java
new loginAccess().execute();
}
//code to check online details
private boolean isOnline(Context mContext) {
ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting())
{
return true;
}
return false;
}
//Close code that check online details
});
//Close log in
}
class loginAccess extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
// Check for success tag
int success;
String username = user.getText().toString();
String password = pass.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST",
params);
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Login Successful!", json.toString());
// Clear all previous data in database
String dar=json.getString(DAIRY);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("logged", "logged");
editor.putString("username", username);
editor.putString("dairy", dar);
editor.commit();
Intent i = new Intent(getApplicationContext(),Menu.class);
finish();
startActivity(i);
// Close all views before launching Dashboard
return json.getString(TAG_MESSAGE);
} else {
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
if(flag==1)
Toast.makeText(MainActivity.this,"Please Enter Correct informations", Toast.LENGTH_LONG).show();
}
}
}
public class Menu extends Activity {
private List<list> myCars = new ArrayList<list>();
int flag=0;
String namee ,dar;
JSONParser jsonParser = new JSONParser();
private ProgressDialog pDialog;
private static final String TAG_SUCCESS = "success";
private static String LOGIN_URL = "http://10.0.2.2/wordtinss/login.php";
private static final String dairy= "dairy";
private static final String TAG_MESSAGE = "message";
public static final String PREFS_NAME = "LoginPrefs";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
populateCarlist();
populateListView();
registerclick();
SharedPreferences un = PreferenceManager.getDefaultSharedPreferences(Menu.this);
namee = un.getString("username", "anon");
TextView usern= (TextView) findViewById(R.id.usern);
usern.setText(namee);
}
}
Use:
namee = getSharedPreferences(PREFS_NAME , Context.MODE_PRIVATE).getString("username", "anon");
instead. Because I think you're using different preference files.
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);
}
}
}
}
I have one database file whose name is menu.db and this file is located at server now i want to read data from this database.
i also have registration page on the application i am working on, as user press submit button then all the user information should be store on that database at server.
if anyone solved this problem then please help me.
if any one knows then please help me.
I have the following code. It authenticates the user password. you should call this method inside doBackground() of AsyncTask extended Class.
public boolean authenticate(String strUsername, String strPassword)
{
boolean bReturn = false;
InputStream pInputStream = null;
ArrayList<NameValuePair> pNameValuePairs = new ArrayList<NameValuePair>();
pNameValuePairs.add(new BasicNameValuePair("userid", strUsername));
pNameValuePairs.add(new BasicNameValuePair("password", strPassword));
try
{
HttpClient pHttpClient = new DefaultHttpClient();
String strURL = p_strServerIP + "Login.php";
HttpPost pHttpPost = new HttpPost(strURL);
pHttpPost.setEntity(new UrlEncodedFormEntity(pNameValuePairs));
HttpResponse pHttpResponse = pHttpClient.execute(pHttpPost);
HttpEntity pHttpEntity = pHttpResponse.getEntity();
pInputStream = pHttpEntity.getContent();
BufferedReader pBufferedReader = new BufferedReader(new InputStreamReader(pInputStream,"iso-8859-1"),8);
StringBuilder pStringBuilder = new StringBuilder();
String strLine = pBufferedReader.readLine();
pInputStream.close();
if(strLine != null)
{
if((strLine).equals("permit"))
{
bReturn = true;
}
}
}
catch (Exception e)
{
Log.e("log_tag", "Caught Exception # authenticate(String strUsername, String strPassword):" + e.toString());
}
return bReturn;
}
The class you extend from AsyncTask should be something like
class ConnectionTask extends AsyncTask<String, Void, Boolean>
{
private SharedPreferences mSettings;
private Context mContext;
ConnectionTask(SharedPreferences settings, Context context)
{
mSettings = settings;
mContext = context;
}
protected void onProgressUpdate(Integer... progress)
{
}
protected void onPostExecute(Boolean result)
{
Toast.makeText(mContext, "Authentication over.", Toast.LENGTH_LONG).show();
}
#Override
protected Boolean doInBackground(String... params)
{
pVerifier.authenticate(params[0], params[1]);
return true;
}
}