[Q] EditText on use of SharedPreference displays junkValue - Java for Android App Development

Hello All,
My functionality is.
- When user types his username and for some reason the application goes to onPause, then i should be able to retrieve the last entered data of the user.
-To achieve this, I have used sharedPreferences & PFB my code.
However, when I execute it, I get the restored username value like "[email protected]" and the value keeps changing for obvious reasons.
I have attached screenshot of the wrong value that i am getting during runtime.
Can anyone please help me with this?
public class RegistrationPage extends Activity {
public static final String PREF_uNAME = "MyPrefsFile";
private static final String TAG =RegistrationPage.class.getSimpleName() ;
//Set regPageDetails = new HashSet();
EditText regPage_userName;
EditText regPage_Passwd;
EditText regPage_eMailAddress;
String UserName;
TextView check1;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration_page);
regPage_userName = (EditText) findViewById(R.id.regPage_editText_UserName);
}
@override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.registration_page, menu);
return true;
}
@override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
protected void onResume(){
super.onResume();
SharedPreferences sharedPref_uName = getApplicationContext().getSharedPreferences(PREF_uNAME, MODE_PRIVATE);
Log.d(TAG,"shared preference value - string" + UserName);
regPage_userName.setText(sharedPref_uName.getString(PREF_uNAME, ""), TextView.BufferType.EDITABLE);
//regPage_userName.setText(sharedPref_uName.getString(PREF_uNAME, ""));
Log.d(TAG,"shared preference value - string" + regPage_userName.toString());
}
public void onPause(){
super.onPause();
UserName = regPage_userName.toString();
SharedPreferences sharedPref_uName = getSharedPreferences(PREF_uNAME, MODE_PRIVATE);
SharedPreferences.Editor editor_uName = sharedPref_uName.edit();
editor_uName.putString(PREF_uNAME, UserName);
editor_uName.commit();
}
public void onStop(){
super.onStop();
regPage_userName.setText("");
}
}

You're pulling the I'd of the edittext out of the shared pref instead of the value in it. Read up on shared preference methods. My github has a login page using shared pref, you could see that.

No, problem lies within onPause when he sets username to regPage_username.toString(). It should be regPage_username.getText().toString()
--------------------
Phone: Nexus 4
OS: rooted Lollipop LRX21T
Bootloader: unlocked
Recovery: TWRP 2.8.2.0

Related

[Q] about page switch

I have the menu with 2 options, settings and cancel. The setting will direct to the setting page. Here is the code I wrote so far.
Code:
static final private int SETTINGS = Menu.FIRST;
static final private int CANCEL = Menu.FIRST + 1;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
// Create and add new menu items.
MenuItem itemSet = menu.add(0, SETTINGS, Menu.NONE, "Settings");
MenuItem itemCan = menu.add(0, CANCEL, Menu.NONE, "Cancel");
// Assign icons
itemSet.setIcon(android.R.drawable.ic_menu_preferences);
itemCan.setIcon(android.R.drawable.ic_menu_close_clear_cancel);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item){
super.onOptionsItemSelected(item);
if (item.getItemId()== SETTINGS){
Intent settingIntent = new Intent(this, setting.class);
startActivityForResult(settingIntent, 0);
}
else if (item.getItemId()== CANCEL){
//do nothing
}
return true;
}
the setting class is
Code:
public class setting extends Activity{
private Button browseButton;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.setup);
browseButton = (Button) findViewById(R.id.Btn_Browse);
browseButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
// TODO Auto-generated method stub
Intent fcIntent = new Intent(v.getContext(), filechooser.class);
startActivityForResult(fcIntent, 0);
}
});
}
}
However, I got an error which is about the program stopped unexpectedly....
could anyone advices me where my program get wrong?
Thank you.

[Q] AlertDialog (-> list with a lot of elements) how to handle orientation-change

Hi,
A few weeks ago I started developing an Android app but I've gut one problem
If the user changed the orientation of his phone the Activity is of course newly created. If there is ProgressDialog opened, I simply open a new one and the user does not realize it, but if I show an AlertDialog containing a few hundred elements and the user scrolls a bit he/she will realize it after I recreate the AlertDialog because the dialog will start again with the first element and the user has to scroll newly to the element he wants.
How I handle the "ListDialog":
At first I have two classes which simplify the ListDialog because I use it a few times...
ListDialog class:
Code:
public class ListDialog {
public static int CHOOSE_MODE_ONLINE = 0x01;
public static int CHOOSE_MODE_BOOKMARK = 0x02;
public static int CHOOSE_MODE_LOCAL = 0x03;
public static int CHOOSE_CHAPTER_ONLINE_DOWNLOAD = 0x04;
public static int CHOOSE_CHAPTER_BOOKMARK_DOWNLOAD = 0x05;
public static int CHOOSE_CHAPTER_ONLINE_READ = 0x06;
public static int CHOOSE_CHAPTER_BOOKMARK_READ = 0x07;
public static int CHOOSE_CHAPTER_LOCAL_READ = 0x08;
public static int CHOOSE_CHAPTER_LOCAL_DELETE = 0x09;
public static int GOTO_PAGE = 0x0A;
public static void show(Context context, String title, CharSequence[] elems, final ListMethodInvoker invoker)
{
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(title);
builder.setItems(elems, new DialogInterface.OnClickListener() {
%mail%Override
public void onClick(DialogInterface dialog, int which) {
invoker.invoke(which);
}
});
builder.setOnCancelListener(new OnCancelListener() {
%mail%Override
public void onCancel(DialogInterface dialog) {
invoker.cancel();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
}
ListMethodInvoker class:
Code:
public class ListMethodInvoker {
public void invoke(int id)
{
}
public void cancel()
{
}
}
and now I create the dialog:
Code:
ApplicationController.get().addOpenedDialog(ListDialog.CHOOSE_MODE_ONLINE);
ListDialog.show(OnlineActivity.this,
mangaController.getManga().getMangaName(),
new CharSequence[]{"Add to Bookmarks", "Download a Chapter", "Read a Chapter"},
new ListMethodInvoker()
{
%mail%Override
public void invoke(int id)
{
ApplicationController.get().removeOpenedDialog(ListDialog.CHOOSE_MODE_ONLINE);
switch(id)
{
case 0: addBookmark(mangaController.getManga()); break;
case 1:
ApplicationController.get().addOpenedDialog(ListDialog.CHOOSE_CHAPTER_ONLINE_DOWNLOAD);
handleChapter(ChapterMode.Download);
break;
case 2:
ApplicationController.get().addOpenedDialog(ListDialog.CHOOSE_CHAPTER_ONLINE_READ);
handleChapter(ChapterMode.Read);
break;
}
}
%mail%Override
public void cancel()
{
ApplicationController.get().removeOpenedDialog(ListDialog.CHOOSE_MODE_ONLINE);
}
});
I also add the ID of the dialog to my ApplicationController which allows me to remember if a dialog has been openend and I can recreate it when onCreate(...) is called again.
(The ApplicationController uses the singleton design pattern which always allows me to retrieve the same instance of the ApplicationController.)
Thanks in advance
best regards
mike
btw: If you wonder why I write %mail% instead of the correct symbol, I get the following exception message if I use it: To prevent spam to the forums, new users are not permitted to post outside links in their messages. All new user accounts will be verified by moderators before this restriction is removed.

[Q] My App use API of Google Maps but the map is slow

Hello Boys,
I am a new Android developer and I'm developing an app with the API of Google Maps.
Into an area of the map I place many markers.
The application works correctly, but the map scroolling and the map zoom isn't quick, everything goes slow.
The marker that I have included in the map is in the "png" format image, and his weighs is approximately 600 bytes.
it is possible that many marker object cause low map scrool?
this is the code of my APP:
Code:
plublic class IDC extends MapActivity {
private LocationManager locationManager;
private LocationListener locationListener;
private MapController mc;
private MapView mapView;
private String myPosition;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String errore="";
myPosition="";
try{
mapView = (MapView) findViewById(R.id.mapview);
mc = mapView.getController();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new GPSLocationListener();
//getMyLocation();
MyDBHelper myDB = new MyDBHelper(IDS.this);
Cursor cursor= myDB.query(new String[] { "x", "y", "y2", "w", "k", "latitude", "longitude"});
//Log.i("NOMI", "TOT. NOMI"+cursor.getCount());
List<Overlay> mapOverlays = mapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.mm_20_blue);
MyItemizedOverlay itemizedoverlay = new MyItemizedOverlay(drawable,IDS.this);
List<Address> address = new ArrayList<Address>();
Log.i("TOT TUPLE", " = "+cursor.getCount());
while(cursor.moveToNext()){
String s= cursor.getString(0);
errore=s;
String nome[]=s.split("-");
// Log.i("Pos Colonna NOME", ""+cursor.getColumnIndex("nome"));
// Log.i("Pos. in Colonna", ""+cursor.getString(0));
//address.addAll(gc.getFromLocationName(nome[1], 1));
//Address a= address.get(address.size()-1);
String la=cursor.getString(5);
String lo=cursor.getString(6);
double latitude= Double.parseDouble(la);
double longitude= Double.parseDouble(lo);
int lan= (int)(latitude*1E6);
int lon= (int)(longitude*1E6);
GeoPoint point = new GeoPoint(lan, lon);
String tel1=cursor.getString(1);
String tel2=cursor.getString(2);
String mail=cursor.getString(4);
String web=cursor.getString(3);
String info[]= {tel1,tel2,nome[1],web,mail};
MyOverlayItem overlayitem = new MyOverlayItem(point, "Hello", nome[0], info);
//mc.animateTo(point);
itemizedoverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedoverlay);
}
mapView.setBuiltInZoomControls(true);
mc.setZoom(6);
}catch (Exception e) {
e.printStackTrace();
}
}
}
Code:
public class MyItemizedOverlay extends ItemizedOverlay {
private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
private Context mContext;
private CustomizeDialog customizeDialog;
public MyItemizedOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
}
public MyItemizedOverlay(Drawable defaultMarker, Context context) {
super(boundCenterBottom(defaultMarker));
mContext = context;
}
protected boolean onTap(int index)
MyOverlayItem item = (MyOverlayItem) mOverlays.get(index);
customizeDialog = new CustomizeDialog(mContext);
customizeDialog.setPersonalText(item.getSnippet());
String []info= item.getInfo();
customizeDialog.setT1(info[0]);
customizeDialog.setT2(info[1]);
customizeDialog.setA(info[2]);
customizeDialog.setW(info[3]);
customizeDialog.setM(info[4]);
customizeDialog.show();
return true;
}
protected OverlayItem createItem(int i) {
return mOverlays.get(i);
}
public int size() {
return mOverlays.size();
}
public void addOverlay(OverlayItem overlay) {
mOverlays.add(overlay);
populate();
}
}
what is the problem??....PLEASE, HELP ME!!

SAP webservice consuming

Hi all ,
I am developing an android app to invoke a webservice in SAP side.i have deployed the webservice and i have sucessfully invoked it using soapui.i am connected to my sap network via vpn.when i try to invoke the webservice from eclipse in the emulator.i am getting an warning "UnknownHostException: Unable to resolve host "myhostaddress": No address associated with hostname".
here is the code i used
public class customer_complaint extends Activity {
/** Called when the activity is first created. */
private static String SOAP_ACTION1 = "";
private static String METHOD_NAME1 = "ZfmCoeMob";
private static String NAMESPACE = "urn:sap-com:document:sap:soap:functions:mc-style";
private static String URL = "hypertextprotocol://10.201.52.86:8003/sap/bc/srt/wsdl/bndg_E2C5751FB4DDC7F192D3000E0CB7EB52/wsdl11/allinone/ws_policy/document?sap-language=EN&sap-client=100&sap-user=abap&[email protected]";
Button submit;
EditText editText_Customer,editText_Invoice;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
setContentView(R.layout.customer_complaint);
submit = (Button)findViewById(R.id.submit);
editText_Customer = (EditText)findViewById(R.id.editText_Customer);
editText_Invoice = (EditText)findViewById(R.id.editText_Invoice);
submit.setOnClickListener(new View.OnClickListener()
{
@override
public void onClick(View v)
{
//Initialize soap request + add parameters
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME1);
//Use this to add parameters
request.addProperty("ZfmCoeMob",editText_Customer.getText().toString());
//Declare the version of the SOAP request
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
try {
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
//this is the actual part that will call the webservice
androidHttpTransport.call(SOAP_ACTION1, envelope);
// Get the SoapResult from the envelope body.
// SoapObject result = (SoapObject)envelope.bodyIn;
SoapPrimitive resultString = (SoapPrimitive)envelope.getResponse();
if(resultString != null)
{
//Get the first property and change the label text
// editText_Invoice.setText(result.getProperty(0).toString());
editText_Invoice.setText(resultString.toString());
}
else
{
Toast.makeText(getApplicationContext(), "No Response",Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
is it something wrong due to the url link.but i am able to invoke the same service using soapui.i have attached my wsdl file with this thread.

[Volley] Main UI extremely slow

In my app i just have a splash screen and a main activity. In the main thread i have three EditText boxes and a spinner with a string array. On clicking the Button, input from three EditText and spinner selection is posted to my mysql database. For the button click network operation, i used Volley since its east and i dont have to use AsyncTask which am not familiar with.
Apart from this, on entering the main UI .. app first check for network connectivity using ConnectivityManager class. After onClick app checks for empty/invalid imputs using TextUtils.
Now the problem is that when i run my app, its very slow and taking upto 65mb of RAM. IS something wrong with my code. Should i run something else as AsynTask ? Can someone check my code and refine it .. thank you
SplashActivity.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
public class SplashActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
int SPLASH_TIME_OUT = 5000;
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent i = new Intent(SplashActivity.this, MainActivity.class);
startActivity(i);
finish();
}
}, SPLASH_TIME_OUT);
}
}
Click to expand...
Click to collapse
MainActivity.java
Code:
public class MainActivity extends Activity {
EditText name, phonenumber, address;
Button insert;
RequestQueue requestQueue;
Spinner spinner;
String insertUrl = "localhost";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner s = (Spinner) findViewById(R.id.spinner);
s.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
/* CHECK INTERNET CONNECTION */
boolean mobileNwInfo;
ConnectivityManager conxMgr = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
try { mobileNwInfo = conxMgr.getActiveNetworkInfo().isConnected(); }
catch (NullPointerException e) { mobileNwInfo = false; }
if (!mobileNwInfo) {
Toast.makeText(this, "No Network, please check your connection. ", Toast.LENGTH_LONG).show();
}
/* CHECK INTERNET CONNECTION PROCEDURE DONE */
name = (EditText) findViewById(R.id.editText);
phonenumber= (EditText) findViewById(R.id.editText2);
address = (EditText) findViewById(R.id.editText3);
insert = (Button) findViewById(R.id.insert);
requestQueue = Volley.newRequestQueue(getApplicationContext());
spinner = (Spinner) findViewById(R.id.spinner);
insert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
/* CHECK EMPTY STRING */
EditText txtUserName = (EditText) findViewById(R.id.editText);
EditText txtUserAddress = (EditText) findViewById(R.id.editText3);
EditText txtUserPhone = (EditText) findViewById(R.id.editText2);
String strUserName = name.getText().toString();
String strUserAddress = address.getText().toString();
String strUserPhone = phonenumber.getText().toString();
if(TextUtils.isEmpty(strUserName)) {
txtUserName.setError("You can't leave this empty.");
return;
}
if(TextUtils.isEmpty(strUserPhone)) {
txtUserPhone.setError("You can't leave this empty.");
return;
}
if(TextUtils.isEmpty(strUserPhone) || strUserPhone.length() < 10) {
txtUserPhone.setError("Enter a valid phone number.");
return;
}
if(TextUtils.isEmpty(strUserAddress)) {
txtUserAddress.setError("You can't leave this empty.");
return;
}
/* LOADING PROCESS DIALOG */
final ProgressDialog pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Booking Service ....");
pd.show();
/* REQUEST RESPONSE/ERROR */
StringRequest request = new StringRequest(Request.Method.POST, insertUrl, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
pd.hide();
System.out.println(response);
name.setText("");
phonenumber.setText("");
address.setText("");
Toast.makeText(getApplicationContext(), "Service successfully booked !!", Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
pd.hide();
Toast.makeText(getApplicationContext(), "Error: Please try again later.", Toast.LENGTH_LONG).show();
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> parameters = new HashMap<>();
parameters.put("name", name.getText().toString());
parameters.put("phonenumber", phonenumber.getText().toString());
parameters.put("address", address.getText().toString());
parameters.put("service", spinner.getItemAtPosition(spinner.getSelectedItemPosition()).toString());
return parameters;
}
};
requestQueue.add(request);
}
});
}
}
Well it's hard to say what exactly is wrong with it. Maybe text is to long. You can try to measure each operation performance with System.nanoseconds(easiest) and localize the problem first. It would be easier to say what to do with it.
Yes you should try to figure out what part is causing the problem. Try to cut the code down to essentials and measure the execution time. Maybe you will be able to tell what part exactly is not working as wanted.

Categories

Resources