I have A SharedPreference That I want to save an array list for the next time I open the app. But The next time I start the app it comes up as empty. I execute the save onDestroy because I dont want to push a button. I dont know whats going on. Any help would be appreciated.
I run LoadData() Method inside onCreate() Method.
public void LoadData(){
SharedPreferences sp = getSharedPreferences("SavedArrayList",MODE_PRIVATE);
Gson gson = new Gson();
String json = sp.getString("Arraylist", null);
Type type = new TypeToken<ArrayList<ListItems>>() {}.getType();
if (json != null)items = gson.fromJson(json, type);
}
#Override
protected void onDestroy() {
SharedPreferences sp = getSharedPreferences("SavedArrayList",MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
Gson gson = new Gson();
String json = gson.toJson(items);
editor.putString("Arraylist", json);
editor.apply();
super.onDestroy();
}
All I did was moved it to onPause and onResume now it works fine.
Related
i want select element when i click button.i use IExternalEventHandler ,but i cant use
method: pickobject/pickobjects ,i change the method to pickPoint the hander run success.
event
public class ExecuteEvent : IExternalEventHandler
{
public string ElementId { get; set; }
public void Execute(UIApplication app)
{
UIDocument uidoc = app.ActiveUIDocument;
Autodesk.Revit.DB.Document doc = uidoc.Document;
Autodesk.Revit.UI.Selection.Selection sel = uidoc.Selection;
Autodesk.Revit.DB.Reference re = sel.PickObject(Autodesk.Revit.UI.Selection.ObjectType.Element);
Autodesk.Revit.DB.XYZ point = sel.PickPoint("select");
ElementId = re.GetType().Name;
}
public string GetName()
{
return "ExecuteEvent";
}
}
hander
Exc = new ExecuteEvent();
ExternalHander = ExternalEvent.Create(Exc);
button click
private void Button_Click(object sender, RoutedEventArgs e)
{
ExternalHander.Raise();
SetLabelText(Exc.ElementId);
}
Apparently, the external event handler does not provide you with a valid user interface context. To get such a context, you might want to subscribe to the Idling event instead. That event is called when Revit has nothing else to do and hence is free to interact with the user.
I have a class to take data from a database and every time I create a variable in the debug mode the name of the variable appears with the message 'this' is not available and I cannot save any type of data in it.
public class DatosPerfilUsuario {
RequestQueue requestQueue;
SharedPreferencias sharedPreferencias = new SharedPreferencias();
String[] StringSplit;
public void RetirarPerfilUsuario(final Context context, final ImageView imageView, final EditText nombre, final EditText nombreusuario, final EditText sexo, final EditText edad, final EditText email, final EditText bio){
StringRequest getRequest = new StringRequest(Request.Method.POST, DatosBase.CONEXION_DB_RETIRAR_PERFILUSUARIO, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(response.equals("0")){
}else {
StringSplit = response.split("/");
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
protected Map<String,String> getParams(){
Map<String, String> params = new HashMap<String, String>();
params.put("NombreUsuario",sharedPreferencias.obtenerValorString(context,"Usuario").toLowerCase());
return params;
}
};
requestQueue = Volley.newRequestQueue(context);
requestQueue.add(getRequest);
}
Code
This situation happens to me with each type of variable that I create int, string, bool ...
I have different classes that do the same, but the problem only arises in this.
I have looked for a solution to the problem in google but there is very little information about this problem, if someone has the solution or understands why this problem is due I would appreciate your help.
UPDATED
It looks like this is not preventing you from compiling and running the code, only that you can't view the variable's contents in the debug window. Sorry. This is not uncommon. The debugger can't determine the this in the current context.
It looks like you may be using Android Studio? If so, check this: https://stackoverflow.com/a/37273436/12431728
OLD / WRONG
Your Response.Listener<String> is an anonymous class, so this refers to the anonymous class. Since StringSplit is a field of the outer class, you should be able to access it as:
OuterClassName.this.StringSplit = ...
Where OuterClassName is the name of the class that contains this code (and StringSplit).
While working on an android app, I discovered, that I would have to use SharedPreferences to store login data (url, port, name), but since I am new to this, I am not sure, how to access the data for MQTT to use those inputs and login.
in tab3_fragment.java, the SharedPreferences get set this way:
public void saveData(){
SharedPreferences userDetails = (SharedPreferences) getContext().getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = userDetails.edit();
editor.putString(url, input_url.getText().toString());
editor.putString(port, input_port.getText().toString());
editor.apply();
Toast.makeText(getActivity(), "Einstellungen gespeichert", Toast.LENGTH_SHORT).show();
}
public void loadData(){
SharedPreferences userDetails = getContext().getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE);
text_url = userDetails.getString(url, " ");
text_port = userDetails.getString(port, " ");
}
This is how I try to access the SharedPreferences:
public MqttHelper(Context context){
SharedPreferences userDetails = getContext().getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE);
final String url = userDetails.getString(tab3_fragment.url, " ");
final String port = userDetails.getString(tab3_fragment.port, " ");
String strArray2[] = {url, port};
String serverUri = TextUtils.join(":", strArray2);
Toast.makeText(getActivity(), serverUri, Toast.LENGTH_SHORT).show();
When running the above code from within another fragments onCreateView, it runs fine, but when I add the code to the MqttHelper.java, so that it can load the settings, it returns error
cannot resolve method `getContext()`.
How can I make the MqttHelper access the SharedPreferences?
When running the above code from within another fragments onCreateView, it runs fine, but when I add the code to the MqttHelper.java, so that it can load the settings, it returns error
cannot resolve method getContext().
As I can see in your code you are passing the context already by parameter, so I don't see any need to use getContext() there, you can easy use context
Bad
public MqttHelper(Context context){
SharedPreferences userDetails = getContext().getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE);
Good
public MqttHelper(Context context){
SharedPreferences userDetails = context.getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE);
Also I'm seeing that you are displaying a Toast using getActivity() you can use also getActivity() to get the context as an alternative.
My app is a list of element names. Clicking one goes to another activity with more details, and an editText and button to change its name. When I go back to the list, I want it to have the new name if updated. My onCreate method has this code which populates it from the database perfectly (ignore the hardcoded size, its just simpler for debugging)
final String DATABASE_NAME = "element_db";
final AppDatabase appDatabase;
appDatabase = Room.databaseBuilder(getApplicationContext(), AppDatabase.class, DATABASE_NAME).build();
ListView list = (ListView)findViewById(R.id.listView);
final String[] element = new String[3];
new Thread(new Runnable() {
#Override
public void run() {
List<Element> elements;
elements = appDatabase.elementDao().fetchElements(); // a dao query "select*from"
int size = elements.size();
for (int i = 0; i < size; i++){
element[i] = elements.get(i).getName();
}
}
}) .start();
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, R.layout.activity_list_view, R.id.textView, element);
list.setAdapter(arrayAdapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(MainActivity.this, itemdetail.class);
i.putExtra("pos", position);
startActivity(i);
}
});
To achieve an updated list when returning to this screen, I copied the above code into the onRestart method, but now the database does not return anything. If I just set the array that goes into the adapter to {"a", "a", "a"} the list populates fine. Any ideas why the database works onCreate but not onRestart?
I think you can use ViewModel and livedata to observe any database change
I developed RssFeed Application using LWUIT j2me(java) for 2 xml files, now I want to show those 2 xml files on LWUIT Tabs.
That means, when my application runs, default tab will be displayed (on that tab my first Rss xml file Titles should be displayed), and when the user click on tab2 my second Rss xml titles should be displayed.
I am able to display the same titles of one rss files on both the tabs, how to control my flow to achieve my task?
Here my code:
public class XMLMidlet extends MIDlet implements ActionListener {
public XMLMidlet() {
Display.init(this);
news = new Vector();
m_backCommand = new Command("Back");
cmdExit = new Command("EXIT");
cmdDetails = new Command("Details");
}
public void startApp() {
//RssFeed URL's
String urls[] = {"http://topnews-23.rss",
"http://topstory-12.rss"};
for(int i=0;i<urls.length;i++){
ParseThread myThread = new ParseThread(this,urls[i]);
//this will start the second thread
myThread.getXMLFeed(urls[i]);
}
}
//method called by the parsing thread
public void addNews(News newsItem,String url) {
try{
news.addElement(newsItem);
form1 = new Form();
myNewsList = new List(newsVector);
newsList =new List(newsVector);
myNewsList.setRenderer(new NewsListCellRenderer());
newsList.setRenderer(new NewsListCellRenderer());
tabs=new Tabs(Component.TOP);
tabs.addTab("TopNews", myNewsList);
tabs.addTab("Topstory",newsList);
form1.addComponent(tabs);
form1.show();
}
catch(Exception e){
e.printStackTrace();
}
}
You should move below code
myNewsList = new List(newsVector);
newsList =new List(newsVector);
myNewsList.setRenderer(new NewsListCellRenderer());
newsList.setRenderer(new NewsListCellRenderer());
tabs=new Tabs(Component.TOP);
form1 = new Form();
tabs=new Tabs(Component.TOP);
tabs.addTab("TopNews", myNewsList);
tabs.addTab("Topstory",newsList);
from addNews method to constructor XMLMidlet. addNews method should use url parameter to differ for which list the newsItem is directed.
Update
Below is how I think you should implement addNews method:
public void addNews(News newsItem, String url) {
if (url.endsWith("topnews-20.rss")) {
myNewsList.addElement(newsItem);
} else if (url.endsWith("topstory-25.rss")) {
newsList.addElement(newsItem);
}
}
serRenderer does not need to be called from addNews and form1.show() should be moved to startApp.