This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I have created a login and trying to save the UserName and UserID for
session but I am getting an error at this line
mAppPreference.setUserID(userid);
The error is :-
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.android.mivas.AppContoller.AppPreference.setUserID(java.lang.String)' on a null object reference
here is my Login class
public class LoginPagefrag extends Fragment implements OnClickListener, MiFeelingBase
{
private Intent i;
private int urlIndex=0;
private Button btnLogin;
private EditText edUserName,edPassword;
private String strUserName,strPassword;
private String strEmailID;
private MultipartEntity reqEntity;
private Dialog dialog;
private ProgressDialog pDialog;
Context cxt;
private SessionManager session;
SharedPreferences myPriference;
AppPreference mAppPreference;
public static final String TAG_USERID = "userid";
public static String TAG_USERNAME = "username";
private static final Pattern EMAIL_PATTERN = Pattern.compile("^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.loginpage, container, false);
APIAccess.fetchData(LoginPagefrag.this, getActivity(), getActivity());
btnLogin=(Button)rootView.findViewById(R.id.btnLogin);
edUserName=(EditText)rootView.findViewById(R.id.edUserName);
edPassword=(EditText)rootView.findViewById(R.id.edPassword);
btnLogin.setOnClickListener(this);
return rootView;
}
#SuppressWarnings("unused")
private void initialiseNoramlVariable() {
cxt = getActivity();
mAppPreference = AppPreference.getInstance(cxt);
}
public void postLogin()
{
try
{
StringBody username=new StringBody(strUserName);
StringBody password=new StringBody(strPassword);
reqEntity = new MultipartEntity();
reqEntity.addPart("username", username);
reqEntity.addPart("password", password);
}
catch(Exception e)
{
System.out.println("err" + e);
}
}
public void postForgotPass()
{
try
{
StringBody emailid=new StringBody(strEmailID);
reqEntity = new MultipartEntity();
reqEntity.addPart("email", emailid);
}
catch(Exception e)
{
System.out.println("err" + e);
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId())
{
case R.id.btnLogin :
if(edUserName.getText().toString().equalsIgnoreCase(""))
{
// Toast.makeText(LoginPagefrag.this, "enter username", Toast.LENGTH_SHORT).show();
}else if(edPassword.getText().toString().equalsIgnoreCase(""))
{
//Toast.makeText(LoginPagefrag.this, "enter pass", Toast.LENGTH_SHORT).show();
}else
{
strUserName=edUserName.getText().toString();
strPassword=edPassword.getText().toString();
urlIndex=0;
APIAccess.fetchData(LoginPagefrag.this, getActivity(), getActivity());
}
break;
}
}
#Override
public String httpPost() {
// TODO Auto-generated method stub
String response="";
if(urlIndex==0)
{
postLogin();
response=APIAccess.openConnection(StaticData.SABAKUCH_LOGIN, reqEntity);
}
return response;
}
#Override
public String httpAfterPost(String str) {
// TODO Auto-generated method stub
if(str!=null)
{
if(urlIndex==0)
{
if(SabaKuchParsechat.jsonStatus(str)==0)
{
// Toast.makeText(LoginPagefrag.this, SabaKuchParsechat.jsonErrorMessage(str), Toast.LENGTH_SHORT).show();
}
else if(SabaKuchParsechat.jsonStatus(str)==1)
{
LoginData obj=SabaKuchParsechat.parseLoginData(str);
Log.d("objj", "hello"+obj);
String userid = obj.strUserId;
String username= obj.strUserName;
mAppPreference.setUserID(userid);
mAppPreference.setUserName(username);
mAppPreference.setServerKey();
session.setLogin(true);
Intent iintt = new Intent(getActivity(),MainActivity.class);
startActivity(iintt);
}
}
}
return null;
}
private boolean CheckEmail(String email) {
return EMAIL_PATTERN.matcher(email).matches();
}
public ConnectivityManager getSystemService(String connectivityService) {
// TODO Auto-generated method stub
return null;
}
}
Here is my AppPreference class :-
public class AppPreference extends Application {
Context cxt;
private static final String SHARED_APP_PREFERENCE_NAME = "sabakuchapp_pref_key";
public static AppPreference mAppprefernce;
private SharedPreferences pref;
private Editor mEditor;
public AppPreference() {
super();
// TODO Auto-generated constructor stub
}
enum SharedPreferenceKey{
USER_ID, USER_NAME, SERVER_KEY;
}
private AppPreference (Context context){
pref = context.getSharedPreferences(SHARED_APP_PREFERENCE_NAME, Context.MODE_PRIVATE);
mEditor = pref.edit();
}
public AppPreference(Context cxt, SharedPreferences pref, Editor mEditor) {
super();
this.cxt = cxt;
this.pref = pref;
this.mEditor = mEditor;
}
public static AppPreference getInstance(Context context){
if(mAppprefernce == null){
mAppprefernce = new AppPreference(context);
}
return mAppprefernce;
}
public void setUserID(String id){
mEditor.putString(SharedPreferenceKey.USER_ID.toString(), id);
mEditor.commit();
}
public String getUserID(){
return pref.getString(SharedPreferenceKey.USER_ID.toString(), "");
}
public void setUserName(String name){
mEditor.putString(SharedPreferenceKey.USER_NAME.toString(), name);
mEditor.commit();
}
public String getUserName(){
return pref.getString(SharedPreferenceKey.USER_NAME.toString(), "");
}
public void setServerKey(){
String original = getUserID()+"_" + getUserName() + "_SBK";
MessageDigest md;
try {
md = MessageDigest.getInstance("MD5");
md.update(original.getBytes());
byte[] digest = md.digest();
StringBuffer sb = new StringBuffer();
for (byte b : digest) {
sb.append(String.format("%02x", b & 0xff));
}
mEditor.putString(SharedPreferenceKey.SERVER_KEY.toString(), sb.toString());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
mEditor.putString(SharedPreferenceKey.SERVER_KEY.toString(), "");
}
mEditor.commit();
return;
}
public String getServerKey(){
return pref.getString(SharedPreferenceKey.SERVER_KEY.toString(), "");
}
}
Please let me know what I am missing here. Thanks in advance.
#SuppressWarnings("unused")
private void initialiseNoramlVariable() {
cxt = getActivity();
mAppPreference = AppPreference.getInstance(cxt);
}
You added "unused" warning by yourself. And you never call this method in fact. So mAppPreference is null. If this method is useless, move mAppPreference = AppPreference.getInstance(cxt); to somewhere else such as onCreateView to make sure it could be inited.
You need to initialize your variable mAppPreference.
I mean you have done that in method initialiseNoramlVariable() but never called the method. You should call the method in onCreateView()
You are not calling initialiseNoramlVariable method and therefor mAppPreference does not get initialized.
This should get you going:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.loginpage, container, false);
APIAccess.fetchData(LoginPagefrag.this, getActivity(), getActivity());
btnLogin=(Button)rootView.findViewById(R.id.btnLogin);
edUserName=(EditText)rootView.findViewById(R.id.edUserName);
edPassword=(EditText)rootView.findViewById(R.id.edPassword);
btnLogin.setOnClickListener(this);
cxt = getActivity();
mAppPreference = AppPreference.getInstance(cxt);
return rootView;
}
Related
I have a listview which consist of image.Now i want to check whether user is logged in or not for every image click.
Here is an CustomStatusGrid.java:
package com.example.kalpesh.statuscollection.Status.Adapter;
import java.util.ArrayList;
import static com.example.kalpesh.statuscollection.LoginActivity.MY_PREFS_NAME;
/**
* Created by Kalpesh on 12/9/2017.
*/
public class CustomStatusGrid extends BaseAdapter {
private Context mContext;
ArrayList<StatusFrmCatResponse_Model> arrayList = new ArrayList<>();
public static final String MY_PREFS_NAME = "MyPrefsFile";
protected static final SharedPreferences settings = null;
public CustomStatusGrid(Context c, ArrayList<StatusFrmCatResponse_Model> arrayList) {
mContext = c;
this.arrayList = arrayList;
}
public int getCount() {
// TODO Auto-generated method stub
return arrayList.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View grid;
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
grid = new View(mContext);
grid = inflater.inflate(R.layout.grid_status, null);
TextView txt_StatusName = (TextView) grid.findViewById(R.id.txt_StatusName);
txt_StatusName.setText(arrayList.get(position).getStatusName());
//TextView txt_status = (TextView) grid.findViewById(R.id.txt_StatusId);
//final String StatusID =txt_status.toString();
ImageView imageClick = (ImageView) grid.findViewById(R.id.ImgAddtoFav);
imageClick.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
}
});
}
else {
grid = (View) convertView;
}
return grid;
}
}
Here is an LoginActivity.java :
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
ArrayList<LoginUserResponse_Model> arrayList=new ArrayList<>();
private static final String TAG = LoginActivity.class.getSimpleName();
private EditText editTextUsername, editTextPassword;
private UserInfo userInfo;
private Session session;
private Button login;
public static final String MY_PREFS_NAME = "MyPrefsFile";
protected static final SharedPreferences settings = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
editTextUsername = (EditText) findViewById(R.id.email);
editTextPassword = (EditText) findViewById(R.id.password);
userInfo = new UserInfo(this);
login = (Button)findViewById(R.id.login);
login.setOnClickListener(this);
findViewById(R.id.link_Register).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//if user pressed on login
//we will open the login screen
finish();
startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
}
});
}
private void login(final String email, final String password){
final String username = editTextUsername.getText().toString();
final String password1 = editTextPassword.getText().toString();
//validating inputs
if (TextUtils.isEmpty(username))
{
editTextUsername.setError("Please enter your Email");
editTextUsername.requestFocus();
return;
}
/* if (!android.util.Patterns.EMAIL_ADDRESS.matcher(Email).matches()) {
email.setError("Enter a valid email");
email.requestFocus();
return;
}*/
if (TextUtils.isEmpty(password1))
{
editTextPassword.setError("Please enter your password");
editTextPassword.requestFocus();
return;
}
// Tag used to cancel the request
String tag_string_req = "req_login";
//progressDialog.setMessage("Logging in...");
// progressDialog.show();
String URL = "http://api.statuscollection.in/api/login";
StringRequest strReq = new StringRequest(Request.Method.POST,
URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.wtf(TAG, "Login Response: " + response.toString());
try {
JSONObject jsonObject = new JSONObject(response);
JSONObject datajsonObject = jsonObject.getJSONObject("data");
LoginUserResponse_Model getDetailStatusModel= new LoginUserResponse_Model();
getDetailStatusModel.setCostamarId(datajsonObject.getString("CostamarId"));
getDetailStatusModel.setEmail(datajsonObject.getString("Email"));
getDetailStatusModel.setPassword(datajsonObject.getString("Password"));
String CostamarId = getDetailStatusModel.setCostamarId(datajsonObject.getString("CostamarId"));
Log.wtf("LoginActivity", "CostamarId " + datajsonObject.getString("CostamarId"));
Log.wtf("LoginActivity", "Email " + datajsonObject.getString("Email"));
Log.wtf("LoginActivity", "Password " + datajsonObject.getString("Password"));
Toast.makeText(LoginActivity.this, "You are Login Successfuly !!!", Toast.LENGTH_LONG).show();
// String CID =arrayList.get(CostamarId);
SharedPreferences settings = getSharedPreferences(MY_PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("logged", true);
// set it to false when the user is logged out
editor.putString("CostamarId",CostamarId);
// Commit the edits!
editor.commit();
SharedPreferences.Editor editor1 = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor1.putString("CostamarId",CostamarId);
Intent intent = new Intent(LoginActivity.this,ForgetPasswordActivity.class);
//intent.putExtra("CUSTID",CostamarId);
startActivity(intent);
finish();
} catch (JSONException e) {
// JSON error
e.printStackTrace();
toast("Json error: " + e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
toast("Unknown Error occurred");
//progressDialog.hide();
//progressDialog.hide();
//progressDialog.hide();
//progressDialog.hide();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<>();
params.put("email", email);
params.put("password", password);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<>();
// headers.put("Content-Type", "application/x-www-form-urlencoded");
headers.put("Authentication", "5vLGpxfO4_FktAkPB0iM--FQh18USYEG7LWWUCbITpGioOZ16QRxe0JuoryqhMHArMcv-lBleaddcJPG3bsj3m94qOke3uq3mXDtvPUZHFkqm9_3Eub7MYlVCudtd8i_qxnFYQFVV8OTNfQ4w01vDjwBvJI2zVUXl8M-A9YfH09sPslbJKyZUBZBNcAqjSOzeIneaNVPH0WWcBP9xx_GvsvISNLWAM1KWlSia5Kb7Glj2ufmdZwl_XE5h1C_0guL5AkJniyLK1cCFjOXH7dgjJA6vjwgc0ol488TyWPWA19sOzsdPrnuzr724-BK3Z84");
return headers;
}
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}
};
strReq.setRetryPolicy(
new DefaultRetryPolicy(
DefaultRetryPolicy.DEFAULT_TIMEOUT_MS,
0,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Adding request to request queue
MySingleton.getInstance(LoginActivity.this).addToRequestQueue(strReq);
}
private void toast(String x){ Toast.makeText(this, x, Toast.LENGTH_SHORT).show();}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.login:
String uName = editTextUsername.getText().toString().trim();
String pass = editTextPassword.getText().toString().trim();
login(uName,pass);
break;
case R.id.buttonRegister:
startActivity(new Intent(this, RegisterActivity.class));
break;
}
}
public void Login_cancel(View view) {
editTextUsername.setText("");
editTextPassword.setText("");
}
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
Help me on android SharedPreferences, I have login activity when after login will set the SharedPreferences, but when set SharedPreferences always error null pointer. I try to show the value with toast and all variable have value. this my activity
public class LoginNewActivity extends Activity {
public SessionManager session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView toRegister = (TextView) findViewById(R.id.link_to_register);
toRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), RegisterActivity.class);
startActivity(i);
}
});
final EditText etUsnm = (EditText) findViewById(R.id.tuserid);
final EditText etPswd = (EditText) findViewById(R.id.tpasswd);
Button bLogin = (Button) findViewById(R.id.btnLogin);
bLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String username = etUsnm.getText().toString();
String password = etPswd.getText().toString();
new UserLoginTask().execute(username, password);
}
});
}
public class UserLoginTask extends AsyncTask<String, String, JSONObject> {
ProgressDialog pdLoading = new ProgressDialog(LoginNewActivity.this);
HttpURLConnection conn;
URL url = null;
JSONParser jsonParser = new JSONParser();
private static final String TAG_MESSAGE = "message";
private static final String TAG_NAMA = "nama_user";
private static final String TAG_USERNAME = "username";
private static final String TAG_HAKAKSES = "role";
private static final String TAG_ERROR = "error";
private static final String LOGIN_URL = "http://192.168.1.101/mlls/getLoginNew.php";
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected JSONObject doInBackground(String... args) {
try {
HashMap<String, String> params = new HashMap<>();
params.put("username", args[0]);
params.put("password", args[1]);
Log.d("request", "starting");
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
if (json != null) {
Log.d("JSON result", json.toString());
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(JSONObject json) {
String nama = "";
int iduser = 0;
String email = "";
String hakakses = "";
int error_message = 0;
if (json != null) {
//Toast.makeText(LoginActivity.this, json.toString(),
//Toast.LENGTH_LONG).show();
try {
nama = json.getString(TAG_NAMA);
email = json.getString(TAG_USERNAME);
hakakses = json.getString(TAG_HAKAKSES);
error_message = json.getInt(TAG_ERROR);
} catch (JSONException e) {
e.printStackTrace();
}
}
if(error_message == 1) {
pdLoading.dismiss();
session.setLogin(true);
session.setStatus(hakakses);
session.setNama(nama);
session.setUsername(email);
session.setId(iduser);
Toast.makeText(LoginNewActivity.this, hakakses,
Toast.LENGTH_LONG).show();
//Intent intent = new Intent(LoginNewActivity.this, LessonListActivity.class);
//intent.putExtra("nama", nama);
//intent.putExtra("email", email);
//intent.putExtra("hakakses", hakakses);
//startActivity(intent);
//LoginNewActivity.this.finish();
}else{
Toast.makeText(getApplicationContext(), "User ID atau Password anda salah.", Toast.LENGTH_LONG).show();
}
}
}}
and this is my sharedPreferences
public class SessionManager {
private static String TAG = SessionManager.class.getSimpleName();
SharedPreferences pref;
Editor editor;
Context _context;
int PRIVATE_MODE = 0;
private static final String PREF_NAME = "Hlls";
private static final String KEY_IS_LOGGEDIN = "isLoggenIn";
private static final String KEY_IS_USER = "isStatus";
private static final String KEY_IS_NAMA = "isNama";
private static final String KEY_IS_USERNAME = "isUsername";
private static final String KEY_IS_IDUSER = "isIdUser";
public SessionManager(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void setLogin(boolean isLoggedIn){
editor.putBoolean(KEY_IS_LOGGEDIN, isLoggedIn);
editor.commit();
Log.d(TAG, "User login session modified");
}
public void setId(int isIdUser){
editor.putInt(KEY_IS_IDUSER, isIdUser);
editor.commit();
Log.d(TAG, "ID User akses session modified");
}
public void setStatus(String isStatus){
editor.putString(KEY_IS_USER, isStatus);
editor.commit();
Log.d(TAG, "User akses session modified");
}
public void setNama(String isNama){
editor.putString(KEY_IS_NAMA, isNama);
editor.commit();
Log.d(TAG, "Username session modified");
}
public void setUsername(String isUsername){
editor.putString(KEY_IS_USERNAME, isUsername);
editor.commit();
Log.d(TAG, "Username session modified");
}
public String isNama(){
return pref.getString(KEY_IS_NAMA, "");
}
public int isId(){
return pref.getInt(KEY_IS_IDUSER, 0);
}
public String isUsername(){
return pref.getString(KEY_IS_USERNAME, "");
}
public boolean isLoggedIn(){
return pref.getBoolean(KEY_IS_LOGGEDIN, false);
}
public String isStatus(){
return pref.getString(KEY_IS_USER, "");
}
}
help me for this error, sorry for bad english
NullPointerException is thrown when an application attempts to use an
object reference that has the null value .
You should call this in your ONCREATE section .
session=new SessionManager(LoginNewActivity.this);
Finally
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
session=new SessionManager(LoginNewActivity.this);
Use mode private instead of private mode
pref = _context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
It is flag provided by android itself you need not assign any other flag to it.
and you have not initialized session manager context is null.
I guess you are not initializing your Shared Preference class.
SessionManager session = new SessionManager(this);
In case its true
Please try and make it a singleton class as a general practise
Something like this
public final class PreferenceManager {
private static SharedPreferences preferences;
/**
* Private constructor to restrict the instantiation of class.
*/
private PreferenceManager() {
throw new AssertionError();
}
public static SharedPreferences getInstance(Context context) {
if (preferences == null && context != null) {
preferences = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
}
return preferences;
}
}
You need to do the following in your Activity:
session = new SessionManager(LoginNewActivity.this);
You have not created the object of your SessionManager class, so its constructor never gets called and you get NPE.
I have an app that shows notification in a listview. I want these notifications to be saved so that if I open the app and see notification I can see these notifications again when I close the app and then open it. I tried this
but nothing was saved.
Another major question is how can I run this app in background? So if notification is received the app lists that notification in the listview without being opened?
My Code
public class MainActivity extends Activity {
ListView list;
CustomListAdapter adapter;
ArrayList<Model> modelList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
modelList = new ArrayList<Model>();
adapter = new CustomListAdapter(getApplicationContext(), modelList);
list=(ListView)findViewById(R.id.list);
list.setAdapter(adapter);
LocalBroadcastManager.getInstance(this).registerReceiver(onNotice, new IntentFilter("Msg"));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);//Menu Resource, Menu
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Intent intent = new Intent(
"android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private BroadcastReceiver onNotice= new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String pack = intent.getStringExtra("package");
String title = intent.getStringExtra("title");
String text = intent.getStringExtra("text");
//int id = intent.getIntExtra("icon",0);
Context remotePackageContext = null;
if (pack.contains("fake")){
try {
// remotePackageContext = getApplicationContext().createPackageContext(pack, 0);
// Drawable icon = remotePackageContext.getResources().getDrawable(id);
// if(icon !=null) {
// ((ImageView) findViewById(R.id.imageView)).setBackground(icon);
// }
byte[] byteArray = intent.getByteArrayExtra("icon");
Bitmap bmp = null;
if (byteArray != null) {
bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
}
Model model = new Model();
if(text.contains("") && !text.contains(" messages")) {
model.setName(title + ": " + text);
model.setImage(bmp);
if (modelList != null) {
modelList.add(model);
adapter.notifyDataSetChanged();
} else {
modelList = new ArrayList<Model>();
modelList.add(model);
adapter = new CustomListAdapter(getApplicationContext(), modelList);
list = (ListView) findViewById(R.id.list);
list.setAdapter(adapter);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
};
}
Make a class Cache which has the capabilities to serialize and deserialize data.
public class Cache {
private static Cache CACHE;
public static Cache get() {
if (!SharedPreferencesHelper.isCacheAvailable()) {
CACHE = new Cache();
SharedPreferencesHelper.saveCache(CACHE);
} else {
CACHE = SharedPreferencesHelper.getCache();
}
return CACHE;
}
ArrayList<Taxonomy> cachedTaxonomies;
public Cache() {
cachedTaxonomies = new ArrayList<Taxonomy>();
}
public ArrayList<Taxonomy> getCachedTaxonomies() {
return cachedTaxonomies;
}
public static String serialize(Cache cache) {
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.enableComplexMapKeySerialization().setPrettyPrinting().create();
return gson.toJson(cache);
}
public static Cache deserialize(String json) {
Type type = new TypeToken<Cache>() {
}.getType();
return new Gson().fromJson(json, type);
}
public void update() {
SharedPreferencesHelper.saveCache(this);
}
}
Here Taxonomy is a model.
Below is the class which helps you save in SharedPrefs
public class SharedPreferencesHelper {
private static final String PREFS_CACHE = "prefs_cache";
public static SharedPreferences getSharedPreferences() {
return SpreeApplication.getSharedPreferences();
}
// Cache -------------------------------------
public static boolean isCacheAvailable() {
SharedPreferences sharedPreferences = getSharedPreferences();
String json = sharedPreferences.getString(PREFS_CACHE, "");
if(json.equals("")) {
return false;
} else {
return true;
}
}
public static Cache getCache() {
SharedPreferences sharedPreferences = getSharedPreferences();
String json = sharedPreferences.getString(PREFS_CACHE, "");
if(json.equals("")) {
return null;
} else {
return Cache.deserialize(json);
}
}
public static void saveCache(Cache cache) {
saveString(PREFS_CACHE, Cache.serialize(cache));
}
// -----------------------------------------------------
private static void saveString(String prefKey, String value) {
SharedPreferences sharedPreferences = getSharedPreferences();
SharedPreferences.Editor prefEditor = sharedPreferences.edit();
prefEditor.putString(prefKey, value);
prefEditor.commit();
}
private static void saveBoolean(String prefKey, boolean value) {
SharedPreferences sharedPreferences = getSharedPreferences();
SharedPreferences.Editor prefEditor = sharedPreferences.edit();
prefEditor.putBoolean(prefKey, value);
prefEditor.commit();
}
}
To save write this :
List<Taxonomy> taxonomies = new ArrayList<Taxonomy>();
Cache cache = Cache.get();
cache.getCachedTaxonomies().clear();
cache.getCachedTaxonomies().addAll(taxonomies);
SharedPreferencesHelper.saveCache(cache);
this is my spreeapplication class which is a custom application class
Remember you have to mention in manifest if you create a custom application class
public class SpreeApplication extends Application{
private final static String DEFAULT_PREFERENCES = "spree";
private static SharedPreferences sharedPreferences;
private static Context applicationContext;
#Override
public void onCreate() {
super.onCreate();
applicationContext = this;
sharedPreferences = getSharedPreferences(DEFAULT_PREFERENCES, Context.MODE_PRIVATE);
}
public static SharedPreferences getSharedPreferences() {
return sharedPreferences;
}
public static SharedPreferences.Editor getSharedPreferencesEditor() {
return sharedPreferences.edit();
}
public static Context getContext() {
return applicationContext;
}
}
In the code below, I took two spinners. One is for brand and other for model. But data is not being displaying in spinner. It is not showing any errors but dropdown is also not shown.
Can any one help me?
What is the mistake in the code?
Java
public class HomeFragment extends Fragment {
public HomeFragment(){}
Fragment fragment = null;
String userId,companyId;
private String brandid = "3";
public static List<LeadResult.Users> list;
public static List<BrandResult.Brands> listBrands;
public static List<ModelResult.Models> listModels;
public static ArrayList<String> listBrands_String;
// public static List<BrandResult.Brands> list1;
String[] brand_name;
Spinner spinner1;
private RelativeLayout mRel_Ownview,mRel_publicview;
private LinearLayout mLin_Stock,mLin_Contact;
private TextView mTxt_OwnView,mTxt_PublicView;
private Map<String, String> BrandMap = new HashMap<String, String>();
private RangeSeekBar<Integer> seekBar;
private RangeSeekBar<Integer> seekBar1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ActionBar actionBar=getActivity().getActionBar();
actionBar.setTitle("DEVINE MECHINES");
SharedPreferences userPreference = getActivity().getSharedPreferences("UserDate", Context.MODE_PRIVATE);
userId=userPreference.getString("MYID", null);
companyId=userPreference.getString("companyId",null);
final View rootView = inflater.inflate(R.layout.layout_ownview, container, false);
spinner1=(Spinner)rootView.findViewById(R.id.brand1);
mTxt_OwnView=(TextView) rootView.findViewById(R.id.txt_OwnView);
mTxt_PublicView =(TextView) rootView.findViewById(R.id.txt_PublicView);
mRel_Ownview=(RelativeLayout)rootView.findViewById(R.id.ownview);
mRel_publicview =(RelativeLayout)rootView.findViewById(R.id.publicview);
listBrands = new ArrayList<BrandResult.Brands>();
listBrands_String = new ArrayList<String>();
listModels = new ArrayList<ModelResult.Models>();
seekBar = new RangeSeekBar<Integer>(5000, 50000,getActivity());
seekBar.setOnRangeSeekBarChangeListener(new RangeSeekBar.OnRangeSeekBarChangeListener<Integer>() {
#Override
public void onRangeSeekBarValuesChanged(RangeSeekBar<?> bar, Integer minValue, Integer maxValue) {
// handle changed range values
//Log.i(TAG, "User selected new range values: MIN=" + minValue + ", MAX=" + maxValue);
TextView seekMin = (TextView) getView().findViewById(R.id.textSeekMin);
TextView seekMax = (TextView) getView().findViewById(R.id.textSeekMax);
seekMin.setText(minValue.toString());
seekMax.setText(maxValue.toString());
}
});
seekBar1 = new RangeSeekBar<Integer>(5000, 50000,getActivity());
seekBar1.setOnRangeSeekBarChangeListener(new RangeSeekBar.OnRangeSeekBarChangeListener<Integer>() {
#Override
public void onRangeSeekBarValuesChanged(RangeSeekBar<?> bar, Integer minValue, Integer maxValue) {
// handle changed range values
//Log.i(TAG, "User selected new range values: MIN=" + minValue + ", MAX=" + maxValue);
TextView seekMin = (TextView) getView().findViewById(R.id.textSeekMin1);
TextView seekMax = (TextView) getView().findViewById(R.id.textSeekMax1);
seekMin.setText(minValue.toString());
seekMax.setText(maxValue.toString());
}
});
mTxt_OwnView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mRel_publicview.setVisibility(View.GONE);
mTxt_OwnView.setBackgroundColor(getResources().getColor(R.color.light_blue));
mTxt_PublicView.setBackgroundColor(getResources().getColor(R.color.dark_blue));
mTxt_OwnView.setTextColor(getResources().getColor(R.color.text_white));
mTxt_PublicView.setTextColor(getResources().getColor(R.color.light_blue));
mRel_Ownview.setVisibility(View.VISIBLE);
}
});
mTxt_PublicView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mRel_Ownview.setVisibility(View.GONE);
mTxt_PublicView.setBackgroundColor(getResources().getColor(R.color.light_blue));
mTxt_OwnView.setBackgroundColor(getResources().getColor(R.color.dark_blue));
mTxt_OwnView.setTextColor(getResources().getColor(R.color.light_blue));
mTxt_PublicView.setTextColor(getResources().getColor(R.color.text_white));
mRel_publicview.setVisibility(View.VISIBLE);
}
});
String selectedBrandId = BrandMap.get(String.valueOf(spinner1.getSelectedItem()));
// System.out.print(url);
mLin_Stock=(LinearLayout)rootView.findViewById(R.id.stock);
mLin_Stock.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fragment =new StockFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
}
});
mLin_Contact =(LinearLayout)rootView.findViewById(R.id.contacts);
mLin_Contact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// getLead();
fragment = new ContactFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
getLead();
}
});
// add RangeSeekBar to pre-defined layout
ViewGroup layout = (ViewGroup) rootView.findViewById(R.id.layout_seek);
layout.addView(seekBar);
ViewGroup layout1 = (ViewGroup) rootView.findViewById(R.id.layout_seek1);
layout1.addView(seekBar1);
getBrands();
getModels();
return rootView;
}
private void getBrands() {
String brandjson = JSONBuilder.getJSONBrand();
String brandurl = URLBuilder.getBrandUrl();
Log.d("url", "" + brandurl);
SendToServerTaskBrand taskBrand = new SendToServerTaskBrand(getActivity());
taskBrand.execute(brandurl, brandjson);
//Log.d("brandjson", "" + brandjson);
}
private void setBrand(String brandjson)
{
ObjectMapper objectMapper_brand = new ObjectMapper();
try
{
BrandResult brandresult_object = objectMapper_brand.readValue(brandjson, BrandResult.class);
String Brand_result = brandresult_object.getRESULT();
Log.i("Brand_result","Now" + Brand_result);
if(Brand_result.equals("SUCCESS"))
{
listBrands =brandresult_object.getBRANDS();
Log.i("listbrands", "List Brands" + listBrands);
/* for(int i = 0; i < listBrands.size(); i++){
listBrands_String.add(listBrands.get(i).toString());
Log.d("string is",""+ listBrands_String);
}*/
spinner_fn();
// startActivity(new Intent(getActivity().getApplicationContext(), Contact_Activity.class));
}
else
{
Toast.makeText(getActivity().getApplicationContext(), "Unable to load data please try again", Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
e.printStackTrace();
}
// return eNames;
}
public class SendToServerTaskBrand extends AsyncTask<String, String, String>
{
private Context mContext = null;
private ProgressDialog mProgressDialog;
public SendToServerTaskBrand(Context context)
{
mContext = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
mProgressDialog = ProgressDialog.show(mContext, "", "Loading...");
}
#Override
protected String doInBackground(String... params)
{
String Burl = params[0];
String Bjson = params[1];
String Bresult = UrlRequester.post(mContext, Burl, Bjson);
return Bresult;
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
setBrand(result);
Log.i("Result","Brand Result"+result);
if (mProgressDialog.isShowing())
mProgressDialog.dismiss();
}
}
private void getModels() {
String model_url = URLBuilder.getModelUrl();
String model_json = JSONBuilder.getJSONModel(brandid);
Log.d("model_json", "" + model_json);
SendToServerTaskModel taskModel = new SendToServerTaskModel(getActivity());
taskModel.execute(model_url, model_json);
}
private void setModel(String json)
{
ObjectMapper objectMapperModel = new ObjectMapper();
try
{
ModelResult modelresult_object = objectMapperModel.readValue(json, ModelResult.class);
String model_result = modelresult_object.getRESULT();
Log.d("model_result","" + model_result);
if (model_result.equals("SUCCESS"))
{
listModels =modelresult_object.getMODELS();
Log.i("listmodels", " " + listModels);
// startActivity(new Intent(getActivity().getApplicationContext(), Contact_Activity.class));
}
else
{
Toast.makeText(getActivity().getApplicationContext(), "Unable to load data please try again", Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
e.printStackTrace();
}
// return eNames;
}
public class SendToServerTaskModel extends AsyncTask<String, String, String>
{
private Context mContext = null;
private ProgressDialog mProgressDialog;
public SendToServerTaskModel(Context context)
{
mContext = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
mProgressDialog = ProgressDialog.show(mContext, "", "Loading...");
}
#Override
protected String doInBackground(String... params)
{
String url = params[0];
String json = params[1];
String result = UrlRequester.post(mContext, url, json);
return result;
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
setModel(result);
if (mProgressDialog.isShowing())
mProgressDialog.dismiss();
}
}
private void spinner_fn() {
/*ArrayAdapter<String> dataAdapter = ArrayAdapter.createFromResource(getActivity().getBaseContext(),
listBrands_String, android.R.layout.simple_spinner_item);*/
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity().getApplicationContext()
,android.R.layout.simple_spinner_item, listBrands_String);
// ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(), R.array.category_array, android.R.layout.simple_spinner_item);
//dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(dataAdapter);
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long id) {
Log.e("Position new",""+ listBrands_String.get(position));
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
private void getLead()
{
String url = URLBuilder.getLeadUrl();
String json = JSONBuilder.getJSONLead(userId, companyId);
SendToServerTask task = new SendToServerTask(getActivity());
task.execute(url, json);
}
private void setLead(String json)
{
ObjectMapper objectMapper = new ObjectMapper();
try
{
LeadResult result_object = objectMapper.readValue(json, LeadResult.class);
String lead_result = result_object.getRESULT();
Log.d("lead_result","" + lead_result);
if (lead_result.equals("SUCCESS"))
{
list=result_object.getUSERS();
// startActivity(new Intent(getActivity().getApplicationContext(), Contact_Activity.class));
}
else
{
Toast.makeText(getActivity().getApplicationContext(), "Unable to load data please try again", Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
e.printStackTrace();
}
// return eNames;
}
public class SendToServerTask extends AsyncTask<String, String, String>
{
private Context mContext = null;
private ProgressDialog mProgressDialog;
public SendToServerTask(Context context)
{
mContext = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
mProgressDialog = ProgressDialog.show(mContext, "", "Loading...");
}
#Override
protected String doInBackground(String... params)
{
String url = params[0];
String json = params[1];
String result = UrlRequester.post(mContext, url, json);
return result;
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
setLead(result);
if (mProgressDialog.isShowing())
mProgressDialog.dismiss();
}
}
i have search and not found the answer. I want to call startActvity(newintent), but the page not change.
This my code:
public class MainActivity extends Activity {
private TextView IdPeserta, Password;
//private ArrayList<NameValuePair> authentication;
#SuppressWarnings("unused")
//private String temp, _nama = "";
//private readURL rL;
public static String username = "";
public static String password = "";
public static String status = "FALSE";
public void setPassword(String password){
MainActivity.password = password;
}
public void setUsername(String username){
MainActivity.username = username;
}
public void setStatus(String status){
MainActivity.status = status;
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
IdPeserta = (TextView) findViewById(R.id.idPeserta);
Password = (TextView) findViewById(R.id.password);
}
public void Login(View view){
setUsername(IdPeserta.getText().toString());
setPassword(Password.getText().toString());
if((IdPeserta.getText().length() > 0 && Password.getText().length() > 0)){
RestTask task = new RestTask();
task.applicationContext = MainActivity.this;
task.execute();
}else{
Toast.makeText(this,"fill Id Peserta and Password 1", 0).show();
}
}
public void authenticate(){
if(status.equals("TRUE")){
Intent i = new Intent(MainActivity.this, Home.class);
//PendingIntent pending = PendingIntent.getActivity(this, 0, i, 0);
startActivity(i);
finish();
}else if(status.equals("FALSE")){
Log.d("gagal", "coba lagi");
}
}
public static String getService() {
String responseString = null;
String baseurlString = "http://10.0.2.2:8080/UjianServices/authentikasi.php";
RestClient client = new RestClient(baseurlString);
client.AddParam("id_peserta", MainActivity.username);
client.AddParam("password", MainActivity.password);
try {
client.Execute(RequestMethod.POST);
} catch (Exception e) {
Log.d("error", e.getMessage());
//e.printStackTrace();
}
responseString = client.getResponse();
return responseString;
}
public class RestTask extends AsyncTask<Object, Object, Object>{
private ProgressDialog dialog;
protected Context applicationContext;
#Override
protected void onPreExecute() {
this.dialog = ProgressDialog.show(applicationContext, "Calling", "Time Service...", true);
}
#Override
protected void onPostExecute(Object result) {
this.dialog.cancel();
String status = result.toString();
setStatus(status);
authenticate();
}
#Override
protected Object doInBackground(Object... arg0) {
return MainActivity.getService();
}
}
}
When i did not using the RestTask it can change the page. How i change my activity?
because applicationContext is null you have not initialize applicationContext before using it for showing ProgressDialog from onPreExecute .
you need to initialize applicationContext before using for showing ProgressDialog or just use MainActivity.this as :
#Override
protected void onPreExecute() {
applicationContext=MainActivity.this; //<<< initialize context here
this.dialog = ProgressDialog.show(applicationContext,
"Calling", "Time Service...", true);
}