setReadAccess for a user with a null ID. Parse Object - android-studio

I am having a serious block right now and cant figure out how to fix this error. When I try to open my NewTipActivity class the app unfortunately stops. I know where the error is located here is the logCat:
Caused by: java.lang.IllegalArgumentException: cannot setReadAccess
for a user with null id
at com.parse.ParseACL.setReadAccess(ParseACL.java:308)
at com.parse.ParseACL.getDefaultACL(ParseACL.java:61)
at com.parse.ParseObject.setDefaultValues(ParseObject.java:3385)
at com.parse.ParseObject.(ParseObject.java:181)
at com.parse.ParseObject.(ParseObject.java:127)
at com.holyapp.danshinn.wingman_etiquette.Tip.(Tip.java:17)
at com.holyapp.danshinn.wingman_etiquette.NewTipActivity.onCreate(NewTipActivity.java:20)
This is the NewTipActivity Class
public class NewTipActivity extends Activity {
private Tip tip;
#Override
protected void onCreate(Bundle savedInstanceState) {
tip = new Tip();
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
//New Tip Fragment
setContentView(R.layout.activity_new_tip);
FragmentManager manager = getFragmentManager();
Fragment fragment = manager.findFragmentById(R.id.fragmentContainer);
if (fragment == null) {
fragment = new NewTipFragment();
manager.beginTransaction().add(R.id.fragmentContainer, fragment)
.commit();
}
}
public Tip getCurrentTip() {
return tip;
}
}
I am very new to Parse so I know there is something within that that I am missing. I may not have declared my ParseUser GetAuthor() correctly.. Please help thank you

i've similar error and i found the solution in:
SetReadAccess error for new ParseObject
When you setup Parse you have to add:
ParseUser.getCurrentUser().saveInBackground(); // <--- This Line

Related

How to fix setOnClickListener code that causes crash

I am having difficulty in figuring out what is wrong with my code, My code runs when the onclick listener is not yet implemented but once I implement the onclick listener it crashes.
public class menu extends AppCompatActivity implements View.OnClickListener {
private CardView assess, profile, chatbot, breathing;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
assess = (CardView) findViewById(R.id.assess);
profile = (CardView) findViewById(R.id.profile);
chatbot = (CardView) findViewById(R.id.chatbot);
breathing = (CardView) findViewById(R.id.breathing);
// assess.setOnClickListener(this);
// profile.setOnClickListener(this);
// chatbot.setOnClickListener(this);
// breathing.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// Intent i;
//
// switch (v.getId()){
//
//
// case R.id.assess :
// i = new Intent(this,depression_assessment.class);
// startActivity(i);
// break;
}
}
//}
When I tried debugging the codes, these lines are the cause of the crash.
// assess.setOnClickListener(this);
// profile.setOnClickListener(this);
// chatbot.setOnClickListener(this);
// breathing.setOnClickListener(this);
It is where the problem is starting because the code works even though the onclick is blank. When I checked the logs it shows this error
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.thesis/com.example.thesis.menu}:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
androidx.cardview.widget.CardView.setOnClickListener(android.view.View$OnClickListener)'
on a null object reference
You haven't shown enough code, but this could be due to serveral reasons:
This line of code breathing = (CardView) findViewById(R.id.breathing); will look for a view with id breathing inside your activity's layout, and according to the error it is null, which means it did not find it within the same activity's layout, so make sure your cardView is in this activity's layout. Another possible reason is that you might have duplicate Ids in your xml files, in this case,find the duplicate and rename the Ids.

'this' is not available in variables android studio

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).

onLoadFinished() not getting called, but onCreateLoader() is called

I am using CursorLoader to load data from database inside my Fragment, which has a RecyclerView. This fragment is being used inside a ViewPager. The ViewPager is contained inside a ContainerFragment, which in turn is inside an Activity.
The ContainerFragment initializes first 4 loaders out of the 10 required in onActivityCreated(). From the log I can see that the loader(s) are in fact getting created. However, onLoadFinished is not getting called for any of the loaders.
Now the twist comes when I swipe through the ViewPager to the third fragment. Now I see the third loader's onLoadFinished getting called. Now this is probably not called from the fragment but from the PagerAdapter's getItem() method, which in addition to instantiating the fragments, also initializes loaders with their IDs in case they haven't been already.
From all other questions on StackOverflow about onLoadFinished not getting called, I have tried the following solutions which are not working for me:
Using forceLoad()
this.getListView().refreshDrawableState(); -> not tried, and don't understand why this should work. Moreover, I am using RecyclerView.
"Importing the correct class" -> I am using AndroidX, and moreover, the loader does load sometimes. If it was the wrong class, it wouldn't have worked any time right?
"Fragment should use SupportLoaderManager" -> tried replacing in the fragment with getActivity().getSupportLoaderManager. For fragment I think it's just getLoaderManager. It was already working sometimes with just getLoaderManager. (No difference observed)
#onActivityCreated
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
startLoaders();
}
startLoaders()
private void startLoaders() {
while(loaderSeqIndex < CATEGORIES.size() && loaderSeqIndex < 4) {
Bundle bundle = new Bundle();
bundle.putString("category", CATEGORIES.get(loaderSeqIndex));
getLoaderManager().initLoader(loaderSeqIndex++, bundle, this);
}
}
LoaderCallbacks
#NonNull
#Override
public Loader<Cursor> onCreateLoader(int id, #Nullable Bundle args) {
Timber.i("Loader created onCreateLoader called");
CursorLoader loader = ArticleLoader.newCategorizedArticlesInstance(getContext(), args.getString("category"));
loader.registerListener(id, new Loader.OnLoadCompleteListener<Cursor>() {
#Override
public void onLoadComplete(Loader<Cursor> loader, Cursor data) {
int position = loader.getId();
cursorHashMap.put(CATEGORIES.get(position), data);
Timber.i("mPager.getCurrentItem(): " + mPager.getCurrentItem() + " position: " + position);
if (position == mPager.getCurrentItem()) {
ArticleListViewModel model = ViewModelProviders.of(ArticleListContainerFragment.this).get(ArticleListViewModel.class);
model.setCursor(data);
}
}
});
return loader;
}
#Override
public void onLoadFinished(#NonNull Loader<Cursor> loader, Cursor data) {
int position = loader.getId();
cursorHashMap.put(CATEGORIES.get(position), data);
Timber.i("mPager.getCurrentItem(): " + mPager.getCurrentItem() + " position: " + position);
if(position == mPager.getCurrentItem()) {
ArticleListViewModel model = ViewModelProviders.of(this).get(ArticleListViewModel.class);
model.setCursor(data);
// mPagerAdapter.notifyDataSetChanged();
}
}
PagerAdapter's #getView
private class MyPagerAdapter extends FragmentStatePagerAdapter {
...
#Override
public Fragment getItem(int position) {
ArticleListFragment fragment = ArticleListFragment.newInstance();
Bundle bundle = new Bundle();
bundle.putString("category", CATEGORIES.get(position));
bundle.putInt("id",position);
fragment.setArguments(bundle);
// fragment.setCursor(cursorHashMap.get(CATEGORIES.get(position)));
return fragment;
}
...
}
I was expecting timber to print from the #onLoadFinished method just to make sure that it's getting called, which isn't happening.
Something weird that is happening is that:
the cursorHashMap that I am using, get's properly populated I open the app a second time (when refresh doesn't happen). And the cursor get's populated without #onLoadFinished being called.

during execution master detail flow i get 2 errors 1-Error:(77, 24) error: cannot find symbol class ItemListActivity

public static class SimpleItemRecyclerViewAdapter
extends RecyclerView.Adapter<SimpleItemRecyclerViewAdapter.ViewHolder> {
private final ItemListActivity mParentActivity;
private final List<DummyContent.DummyItem> mValues;
private final boolean mTwoPane;
private final View.OnClickListener mOnClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
DummyContent.DummyItem item = (DummyContent.DummyItem) view.getTag();
if (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putString(WebpageDetailFragment.ARG_ITEM_ID, item.id);
WebpageDetailFragment fragment = new WebpageDetailFragment();
fragment.setArguments(arguments);
mParentActivity.getSupportFragmentManager().beginTransaction()
.replace(R.id.webpage_detail_container, fragment)
.commit();
This happens when you change the default item names during the wizard of creating the activity.
just rename the ItemListActivity to the name of your Activity . ( the name of the file that has that code error).
use refactor rename to change it everywhere it's mentioned.
If the ItemListActivity (or whatever you ended up calling it) extends from Activity and not AppCompatActivity then try changing the line
mParentActivity.getSupportFragmentManager().beginTransaction()
to
mParentActivity.getFragmentManager().beginTransaction()

Debugging Package Manager Console Update-Database Seed Method

I wanted to debug the Seed() method in my Entity Framework database configuration class when I run Update-Database from the Package Manager Console but didn't know how to do it. I wanted to share the solution with others in case they have the same issue.
Here is similar question with a solution that works really well.
It does NOT require Thread.Sleep.
Just Launches the debugger using this code.
Clipped from the answer
if (!System.Diagnostics.Debugger.IsAttached)
System.Diagnostics.Debugger.Launch();
The way I solved this was to open a new instance of Visual Studio and then open the same solution in this new instance of Visual Studio. I then attached the debugger in this new instance to the old instance (devenv.exe) while running the update-database command. This allowed me to debug the Seed method.
Just to make sure I didn't miss the breakpoint by not attaching in time I added a Thread.Sleep before the breakpoint.
I hope this helps someone.
If you need to get a specific variable's value, a quick hack is to throw an exception:
throw new Exception(variable);
A cleaner solution (I guess this requires EF 6) would IMHO be to call update-database from code:
var configuration = new DbMigrationsConfiguration<TContext>();
var databaseMigrator = new DbMigrator(configuration);
databaseMigrator.Update();
This allows you to debug the Seed method.
You may take this one step further and construct a unit test (or, more precisely, an integration test) that creates an empty test database, applies all EF migrations, runs the Seed method, and drops the test database again:
var configuration = new DbMigrationsConfiguration<TContext>();
Database.Delete("TestDatabaseNameOrConnectionString");
var databaseMigrator = new DbMigrator(configuration);
databaseMigrator.Update();
Database.Delete("TestDatabaseNameOrConnectionString");
But be careful not to run this against your development database!
I know this is an old question, but if all you want is messages, and you don't care to include references to WinForms in your project, I made some simple debug window where I can send Trace events.
For more serious and step-by-step debugging, I'll open another Visual Studio instance, but it's not necessary for simple stuff.
This is the whole code:
SeedApplicationContext.cs
using System;
using System.Data.Entity;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
namespace Data.Persistence.Migrations.SeedDebug
{
public class SeedApplicationContext<T> : ApplicationContext
where T : DbContext
{
private class SeedTraceListener : TraceListener
{
private readonly SeedApplicationContext<T> _appContext;
public SeedTraceListener(SeedApplicationContext<T> appContext)
{
_appContext = appContext;
}
public override void Write(string message)
{
_appContext.WriteDebugText(message);
}
public override void WriteLine(string message)
{
_appContext.WriteDebugLine(message);
}
}
private Form _debugForm;
private TextBox _debugTextBox;
private TraceListener _traceListener;
private readonly Action<T> _seedAction;
private readonly T _dbcontext;
public Exception Exception { get; private set; }
public bool WaitBeforeExit { get; private set; }
public SeedApplicationContext(Action<T> seedAction, T dbcontext, bool waitBeforeExit = false)
{
_dbcontext = dbcontext;
_seedAction = seedAction;
WaitBeforeExit = waitBeforeExit;
_traceListener = new SeedTraceListener(this);
CreateDebugForm();
MainForm = _debugForm;
Trace.Listeners.Add(_traceListener);
}
private void CreateDebugForm()
{
var textbox = new TextBox {Multiline = true, Dock = DockStyle.Fill, ScrollBars = ScrollBars.Both, WordWrap = false};
var form = new Form {Font = new Font(#"Lucida Console", 8), Text = "Seed Trace"};
form.Controls.Add(tb);
form.Shown += OnFormShown;
_debugForm = form;
_debugTextBox = textbox;
}
private void OnFormShown(object sender, EventArgs eventArgs)
{
WriteDebugLine("Initializing seed...");
try
{
_seedAction(_dbcontext);
if(!WaitBeforeExit)
_debugForm.Close();
else
WriteDebugLine("Finished seed. Close this window to continue");
}
catch (Exception e)
{
Exception = e;
var einner = e;
while (einner != null)
{
WriteDebugLine(string.Format("[Exception {0}] {1}", einner.GetType(), einner.Message));
WriteDebugLine(einner.StackTrace);
einner = einner.InnerException;
if (einner != null)
WriteDebugLine("------- Inner Exception -------");
}
}
}
protected override void Dispose(bool disposing)
{
if (disposing && _traceListener != null)
{
Trace.Listeners.Remove(_traceListener);
_traceListener.Dispose();
_traceListener = null;
}
base.Dispose(disposing);
}
private void WriteDebugText(string message)
{
_debugTextBox.Text += message;
Application.DoEvents();
}
private void WriteDebugLine(string message)
{
WriteDebugText(message + Environment.NewLine);
}
}
}
And on your standard Configuration.cs
// ...
using System.Windows.Forms;
using Data.Persistence.Migrations.SeedDebug;
// ...
namespace Data.Persistence.Migrations
{
internal sealed class Configuration : DbMigrationsConfiguration<MyContext>
{
public Configuration()
{
// Migrations configuration here
}
protected override void Seed(MyContext context)
{
// Create our application context which will host our debug window and message loop
var appContext = new SeedApplicationContext<MyContext>(SeedInternal, context, false);
Application.Run(appContext);
var e = appContext.Exception;
Application.Exit();
// Rethrow the exception to the package manager console
if (e != null)
throw e;
}
// Our original Seed method, now with Trace support!
private void SeedInternal(MyContext context)
{
// ...
Trace.WriteLine("I'm seeding!")
// ...
}
}
}
Uh Debugging is one thing but don't forget to call:
context.Update()
Also don't wrap in try catch without a good inner exceptions spill to the console.
https://coderwall.com/p/fbcyaw/debug-into-entity-framework-code-first
with catch (DbEntityValidationException ex)
I have 2 workarounds (without Debugger.Launch() since it doesn't work for me):
To print message in Package Manager Console use exception:
throw new Exception("Your message");
Another way is to print message in file by creating a cmd process:
// Logs to file {solution folder}\seed.log data from Seed method (for DEBUG only)
private void Log(string msg)
{
string echoCmd = $"/C echo {DateTime.Now} - {msg} >> seed.log";
System.Diagnostics.Process.Start("cmd.exe", echoCmd);
}

Resources