I'm busy with a very basic Note Taking Android App and having trouble with shared preferences.
In MainActivity is(should be) a list of the notes that were previously taken. To make a note you press menu and select make a note, that will take you to the second activity(writeANote.java).From there you make your note press menu and select add note, the it should be in in the listView(noteList). But its not... i think my problem is in MainActivity where I try to get the ArrayList from shared preferences.
I also have the ObjectSerializer class.
Please help.
Here is my code for the MainActivity.
package com.example.makeanote;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
static SharedPreferences sp;
static ListView noteList;
//static ArrayList<String> noteArray;
//static ArrayAdapter<String> adapter;
static ArrayAdapter<String> spListAdapter;
ArrayList<String> newSpList;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater=getMenuInflater();
menuInflater.inflate(R.menu.main_menu,menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
super.onOptionsItemSelected(item);
switch(item.getItemId()){
case(R.id.makeNewNote):
Intent i=new Intent(getApplicationContext(),writeANote.class);
startActivity(i);
Log.i("SELECTED","make New Note");
return true;
default:
return false;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
noteList=(ListView)findViewById(R.id.noteList);
//noteArray= new ArrayList<String>();
//adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,noteArray);
try {
newSpList=(ArrayList<String>)ObjectSerializer.deserialize((sp.getString("spList",ObjectSerializer.serialize(new ArrayList<String>()))));
Log.i("new SP List", newSpList.get(0));
}catch(Exception e){
e.printStackTrace();
}
spListAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,newSpList);
sp= (SharedPreferences) getSharedPreferences("com.example.makeanote", Context.MODE_PRIVATE);
//String test=sp.getString("test","nothing");
newSpList.add("test");
//noteArray.add(test);
if (newSpList.size()!=0) {
noteList.setAdapter(spListAdapter);
}else{
Toast.makeText(this, "No Notes So Far", Toast.LENGTH_SHORT).show();
}
}
}
Here is my code for the second activity(writeANote.java).
package com.example.makeanote;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.EditText;
import java.util.ArrayList;
import static com.example.makeanote.MainActivity.sp;
public class writeANote extends AppCompatActivity {
EditText note;
ArrayList<String> spList;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater=getMenuInflater();
menuInflater.inflate(R.menu.menu_2,menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
super.onOptionsItemSelected(item);
switch(item.getItemId()){
case(R.id.addNote):
//sp.edit().putString("test",).apply();
spList.add(note.getText().toString());
try {
MainActivity.sp.edit().putString("spList",ObjectSerializer.serialize(spList)).apply();
}catch(Exception e){
e.printStackTrace();
}
Intent i=new Intent(getApplicationContext(),MainActivity.class);
startActivity(i);
Log.i("SELECTED","add New Note");
return true;
default:
return false;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_write_a_note);
spList=new ArrayList<>();
note=findViewById(R.id.note);
}
}
Related
I am getting an error for permission in the Bluetooth when I am using the command to disable.
please tell me why it's happening.
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Toast;
import java.util.Set;
public class MainActivity extends AppCompatActivity {
CheckBox enable;
private BluetoothAdapter BA;
private Set<BluetoothDevice> pairedDevices;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
enable = findViewById(R.id.enable_bt);
BA = BluetoothAdapter.getDefaultAdapter();
if (BA == null) {
Toast.makeText(this, "bluetooth not supported", Toast.LENGTH_SHORT).show();
finish();
}
if (BA.isEnabled()) {
enable.setChecked(true);
}
enable.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
BA.disable();
}
}
}
I’ve create this Web View app, but something doesn’t work well. The page is reloaded over and over again. Could you help me to find why it is happens ?
I think this happens when it try to load the body content of the url.
package com.maunexus;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private WebView webView;
Activity activity;
private ProgressDialog progDailog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView=findViewById(R.id.webviewid);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("https://pari365.mg");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.super_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.menu_back:
onBackPressed();
break;
case R.id.menu_forward:
onForwardPressed();
break;
case R.id.menu_refresh:
webView.reload();
Toast.makeText(this, "Reloading... Please Wait!", Toast.LENGTH_SHORT).show();
break;
}
return super.onOptionsItemSelected(item);
}
private void onForwardPressed(){
if (webView.canGoForward()){
webView.goForward();
} else {
Toast.makeText(this, "Already there! ;)", Toast.LENGTH_SHORT).show();
}
}
public void onBackPressed(){
if (webView.canGoBack()){
webView.goBack();
}
}
}
There’s sometimes when the refresh is not happening, but the url does not load in full.
You need to add this line of code for accepting thirdparty cookies
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
CookieManager.getInstance().setAcceptThirdPartyCookies(webView,true);
}
It will work like a charm
as posts are limited in size on this platform I will post in parts first my mainactivity.java file package com.cancunsteve.aboutcancunsteve;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.MainActivity;
import android.NewActivity2;
public class MainActivity extends AppCompatActivity {
Button button;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.MyButton);
button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent myIntent = new Intent(MainActivity.this,
NewActivity2.class);
startActivity(myIntent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
You have to create a NewActivity2 class/activity
Your import is wrong for the NewActivity2, I doubt it is part of the android package.
Hi am using a "Add" button in ActionBar of my app on clicking it a ListView gets open and the user can tap on any list item to add that item to the RecyclerView which is the parent activity(MainActivity holding the Recyclerview) but on exiting the app the last added item stays on MainActivity's view. I guess SharedPreferences' Editor is getting overwritten everytime. Can you please help in providing some snippet as i can't call editor.put() method multiple times as the click happens on listView. My RecyclerView contains an image and a text.
Here is my MainActivity's Code
package com.example.mohitmehndiratta.customlistadap;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Icon;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import static android.support.v7.widget.LinearLayoutManager.*;
public class MainActivity extends AppCompatActivity {
public static ArrayList<DataSet> alist;
int i;
RecyclerView rv;
static RecycledAdap adap;
static String args;
static int rid;
static SharedPreferences sharedPreferences;
public static void addnow(String arg)
{
args=arg;
rid=R.drawable.i;
alist.add(new DataSet(args,rid));
adap.notifyDataSetChanged();
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putInt("Iconid",rid);
editor.putString("AppName",args);
editor.apply();
if (sharedPreferences!=null)
{
int x=sharedPreferences.getInt("Iconid",rid);
String y=sharedPreferences.getString("AppName",args);
addnow(y);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater=getMenuInflater();
inflater.inflate(R.menu.new_menu,menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==R.id.addbtn)
{
Intent intent=new Intent(this,AppList.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreferences = getSharedPreferences("MyPrefs",getApplicationContext().MODE_PRIVATE);
rv=(RecyclerView)findViewById(R.id.rv);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
rv.setLayoutManager(mLayoutManager);
rv.setItemAnimator(new DefaultItemAnimator());
rv.addItemDecoration(new ItemDecoration(this, LinearLayoutManager.VERTICAL));
for(i=0;i<DataModel.name.length;i++) {
alist = new ArrayList<DataSet>();
alist.add(new DataSet("Paytm",R.drawable.i));
alist.add(new DataSet("Facebook",R.drawable.i1));
alist.add(new DataSet("ShareIt",R.drawable.i2));
alist.add(new DataSet("Instagram",R.drawable.i3));
alist.add(new DataSet("BookMyShow",R.drawable.i4));
}
adap=new RecycledAdap(getApplicationContext(),alist);
rv.setAdapter(adap);
MyListener mlistener=new MyListener(getApplicationContext(),rv, new MyListener.ReClickListener() {
#Override
public void onClick(int position) {
Toast.makeText(getApplicationContext(),"Launching item"+position,Toast.LENGTH_SHORT).show();
LauncherHandler lh=new LauncherHandler(position);
String pkname=lh.getpack();
AppDialog adialog=new AppDialog();
adialog.packagenameset(pkname);
adialog.show(getFragmentManager(),"AppDialogFrag");
}
#Override
public void onLongClick(int position) {
LauncherHandler lh=new LauncherHandler(position);
String pkname=lh.getpack();
Toast.makeText(getApplicationContext(),"Launching item"+position,Toast.LENGTH_SHORT).show();
AppDialog adialog=new AppDialog();
adialog.packagenameset(pkname);
adialog.show(getFragmentManager(),"AppDialogFrag");
}
});
rv.addOnItemTouchListener(mlistener);
if (sharedPreferences!=null)
{
int x=sharedPreferences.getInt("Iconid",rid);
String y=sharedPreferences.getString("AppName",args);
addnow(y);
}
else
{
Toast.makeText(getApplication(),"There is nothing in app's cache",Toast.LENGTH_SHORT).show();
}
}
}
ListView code :
package com.example.mohitmehndiratta.customlistadap;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class AppList extends AppCompatActivity {
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_app_list);
PackageManager pm=getPackageManager();
ArrayList<ApplicationInfo> li= (ArrayList<ApplicationInfo>) pm.getInstalledApplications(0);
ArrayList al=new ArrayList<String>();
String str;
String strpk;
ApplicationInfo info;
for(int i=0;i<li.size();i++)
{
info=li.get(i);
str=info.loadLabel(pm).toString();
Drawable appicon=info.loadIcon(pm);
al.add(str);
}
lv=(ListView)findViewById(R.id.listView);
final ArrayAdapter adap=new ArrayAdapter<String>(this,R.layout.support_simple_spinner_dropdown_item,al);
lv.setAdapter(adap);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String text=lv.getItemAtPosition(i).toString();
Toast.makeText(getApplicationContext(),text+i,Toast.LENGTH_SHORT).show();
MainActivity.addnow(text);
}
});
}
}
Please help me out regarding the menu handler . I want to make menu handler which i can call in different activities . All things are working fine . list is fetching from the server and menu are also appearing but when i click on the any menu button "Force to close" Pops up .
Here is the meun handler class
package com.droidnova.android.howto.optionmenu;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.content.Intent;
public class MenuHandler extends Activity{
private Activity activity;
public MenuHandler(Activity activity) {
this.activity = activity;
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = activity.getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.settings:
Intent intent = new Intent(this, ShowSettings.class);
startActivity(intent);
break;
case R.id.services:
Intent intent2 = new Intent(this, Test.class);
startActivity(intent2);
break;
case R.id.Quit:
finish();
break;
default:
break;
}
return true;
}
}
over here i want the same menu to work .
package com.droidnova.android.howto.optionmenu;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class Test extends ListActivity {
private MenuHandler menuHandler;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listplaceholder);
menuHandler = new MenuHandler(this);
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
JSONObject json = JSONfunctions.getJSONfromURL("http://midsweden.gofreeserve.com/fetch.php");
try{
JSONArray earthquakes = json.getJSONArray("earthquakes");
for(int i=0;i<earthquakes.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = earthquakes.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("name", "Earthquake name:" + e.getString("name"));
map.put("password", "Magnitude: " + e.getString("password"));
mylist.add(map);
}
}catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.test,
new String[] { "name", "magnitude" },
new int[] { R.id.item_title, R.id.item_subtitle });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
Toast.makeText(Test.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return menuHandler.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return menuHandler.onOptionsItemSelected(item);
}
}
Here is what i am getting in the logcat
Without any specific logcat feedback about the exception your code is throwing, my best guess is Android doesn't like you crossing multiple Context instances in the way that you are by instantiating one Activity inside of another.
A much better way to accomplish your goal is to use the MenuHandler as the base class for any Activity that you want to display the menu. In other words:
Leave MenuHandler alone, except for getting rid of that constructor.
Make all your Activity classes extend MenuHandler to bring in that functionality.