How to access String outside method - java

I'm trying to access a string outside the parse query, it's not working outside query but it works inside the query.
I declared the global variable and and tried to access it but it's still not working, instead of string it returns null.
I'm new to Java and Android so please forgive me if it's stupid question.
Any help would be appreciated.
public class ActivityQuiz extends AppCompatActivity {
ArrayList<String> answerList = new ArrayList<>();
int c=0;
String Answer = "correct";
String selectedOption;
public static String checkAns;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
ParseQuery<ParseObject> query = ParseQuery.getQuery("Question");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> questions, ParseException e) {
if (e == null) {
for (ParseObject question : questions) {
answerList.add(question.getString(Answer));
checkAns = getanswerList.get(c);
Log.d("String check",""+checkAns); //here it's working
}
} else {
e.printStackTrace();
}
}
});
try{
String checkanswer = checkAns ; // here returns null instead of string
Log.d("String checkans",""+checkanswer);}
catch (Exception e)
{
e.printStackTrace();
Log.d("Error", "Error, Not Working");
}
}

There is very simple problem. In first instance you are getting the value of checkAns from the data after hitting the API (in background). So if data come from API it will be non-null.
In later part, since the API response takes time, try-catch block will be executed before it sets value in checkAns So checkAns is equal to initialised value which is null.
Ideally, you should use the value of checkAns only inside done() method.

add your try-catch code inside ParseQuery like this:
ParseQuery<ParseObject> query = ParseQuery.getQuery("Question");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> questions, ParseException e) {
if (e == null) {
for (ParseObject question : questions) {
answerList.add(question.getString(Answer));
checkAns = getanswerList.get(c);
Log.d("String check",""+checkAns); //here it's working
// ....Add your try catch code.....
try{
String checkanswer = checkAns ; // also working well
Log.d("String checkans",""+checkanswer);}
catch (Exception e)
{
e.printStackTrace();
Log.d("Error", "Error, Not Working");
}
}
} else {
e.printStackTrace();
}
}
});

That is normal behavior for asynchronous functions.
By the time your try/catch block is executed checkanswer is still null because your query takes time to execute. Once done() is executed you'll have your string.
If you must have your value in that block, you can sleep a second or two and check if checkanswer is no longer null. Be careful with sleeps as they will hang your program if you do use them in your main thread

The Problem is that your try catch block will execute befor your query is done means the overriden done method will call and set the checkAns after you execute the try catch block.
If you will use the findInBackground method than make a method in your done method in which you will do all your stuff like:
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> questions, ParseException e) {
if (e == null) {
successful(questions);
} else {
e.printStackTrace();
}
}
});
private void successful(List<ParseObject> questions){
for (ParseObject question : questions) {
answerList.add(question.getString(Answer));
Log.d("String checkans",""+checkanswer);
}
String checkanswer = getanswerList.get(c);
}
else you can use the find() method:
List<ParseObject> questions = query.find();
for (ParseObject question : questions) {
answerList.add(question.getString(Answer));
Log.d("String checkans",""+checkanswer);
}
String checkanswer = getanswerList.get(c);

Related

Context Sensitive help for AbstractGraphicalEditPart(GMF)

the problem is simple: To add Context Sensitive Help i followed the standard steps, but once i try to link the BLOCKS to the CONTEXT IDs with SetHelp() from IWorkbenchHelpSystem. The frist argument should be either a Control(swt) or IAction.
void setHelp(Control control, String helpContextId);. How can i refer to Control from a damos.dml.Block object type ?
org.eclipselabs.damos.dml.blockTypes
FYI
I've tried and visited all the content of these sites
http://rajakannappan.blogspot.com/2009/05/context-sensitive-help-in-eclipse.html
https://help.eclipse.org/2019-03/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2Fguide%2Fua_help_context.htm&cp=2_0_19_1_2
https://help.eclipse.org/luna/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2Freference%2Fextension-points%2Forg_eclipse_ui_commands.html
The display and search methods are working correctly but I just need to set the help and not display it so that only upon calling Help (F1 or ctrl+F1) the context help is shown.
Thanks.
After trying I thought maybe this workaround would get me the same result but NADA.
private Block getBlock() {
EObject semanticElement = resolveSemanticElement();
if (semanticElement instanceof Block) {
Block block = (Block) semanticElement;
PlatformUI.getWorkbench().getHelpSystem().search(block.getType().getName());
//PlatformUI.getWorkbench().getHelpSystem().setHelp(?, Activator.HELP_VIEW); Cannot cast block directly to Control
PlatformUI.getWorkbench().getHelpSystem().displayHelp(Activator.HELP_VIEW);
return block;
} else {
return null;
}
}
#Override
protected NodeFigure createMainFigure() {
blockFigure = new BlockFigure();
// OB: java.awt.event.KeyEvent.VK_F1 is wrong, use SWT.F1
blockFigure.setFocusTraversable(true);
blockFigure.setRequestFocusEnabled(true);
blockFigure.addMouseListener(new MouseListener.Stub() {
#Override
public void mousePressed(final MouseEvent me) {
blockFigure.requestFocus();
}
});
blockFigure.addKeyListener(new KeyListener.Stub() {
#Override
public void keyReleased(KeyEvent ke) {
}
#Override
public void keyPressed(KeyEvent ke) {
if (ke.keycode == SWT.F1) {
PlatformUI.getWorkbench().getHelpSystem().search(getBlock().getType().getName());
PlatformUI.getWorkbench().getHelpSystem().displayHelp(Activator.HELP_VIEW);
}
}
});
return blockFigure;
}
Any help is appreciated!
public String getSelection() {
String blockName = "SelectBlock";
EObject element = null;
EditPart part = getDiagramEditPart();
EditPartViewer viewer = part.getViewer();
List selectedList = viewer.getSelectedEditParts();
try {
GraphicalEditPart editPart = (GraphicalEditPart) selectedList.get(0);
BlockEditPart blockPart = (BlockEditPart) editPart;
viewer.getProperty("BlockFigure");
NodeImpl node = (NodeImpl) blockPart.getModel();
element = node.getElement();
} catch (IndexOutOfBoundsException e) {
// TODO: handle exception
e.printStackTrace();
}
ISelection selection1 = viewer.getSelection();// EURêKA
if (element instanceof Block) {
Control control2 = getGraphicalViewer().getControl();
blockName = ((Block) element).getType().getName();
return blockName;
// return part.getParent().getSelected();
}
return "SelectBlock";
}
i have the possiblity to select a block type CTRL+F1 and voila the Help Definition of said Block is shown.

Parse "no results found for query (code 101)". Can't get object id

I've installed the example parse server (https://github.com/ParsePlatform/parse-server-example) on my desktop and made a simple app to test it.
My app saves an object to the server, gets the object and sets mTextView's value to the value of my object.
The problem is, when I try this code to get data from server it works:
query.getInBackground("5K7N8a8Dmd", new GetCallback<ParseObject>() ...
(got the object id with curl)
but when I try this (to get object id w/o using curl):
gameScore.saveInBackground(new SaveCallback() {
public void done(ParseException e) {
if (e == null) {
objectId = gameScore.getObjectId();
} else {
Log.e("saveInBackground", getErrorMessage(e));
}
}
});
...
query.getInBackground(objectId, new GetCallback<ParseObject>() ...
it doesn't work.
logcat:
E/getInBackground﹕ no results found for query - code: 101
MainActivity.java
public class MainActivity extends Activity {
public TextView mTextView;
public String objectId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) findViewById(R.id.text_view);
Parse.initialize(new Parse.Configuration.Builder(getApplicationContext())
.applicationId(Constants.APP_ID)
.server(Constants.SERVER_URL)
.build()
);
final ParseObject gameScore = new ParseObject("Foo1234");
gameScore.put("score", 5000);
gameScore.saveInBackground(new SaveCallback() {
public void done(ParseException e) {
if (e == null) {
objectId = gameScore.getObjectId();
} else {
Log.e("saveInBackground", getErrorMessage(e));
}
}
});
ParseQuery<ParseObject> query = ParseQuery.getQuery("Foo1234");
query.getInBackground(objectId, new GetCallback<ParseObject>() {
public void done(ParseObject object, ParseException e) {
if (e == null) {
mTextView.setText(Integer.toString(gameScore.getInt("score")));
} else {
Log.e("getInBackground", getErrorMessage(e));
}
}
});
}
public String getErrorMessage(ParseException e) {
return e.getMessage() + " - code: " + e.getCode();
}
}
Constants.java
public class Constants {
public static String SERVER_URL = "http://192.168.1.14:1337/parse/";
public static String APP_ID = "myAppId";
}
Thanks in advance.
Try this
ParseQuery<ParseObject> query = ParseQuery.getQuery("_Foo1234");
query.whereEqualTo("objectId","wfBB0gpCkP");
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
// row of Object Id "wfBB0gpCkP"
} else {
// error
}
}
});
Also change
ParseQuery<ParseObject> query = ParseQuery.getQuery("Foo1234");
to
ParseQuery<ParseObject> query = ParseQuery.getQuery("_Foo1234");
See if this works.
The problem is the "background" part of saveInBackground(). The save isn't complete on the line following the save. In fact, it hasn't even begun to save. The save isn't complete until the completion handler runs.
Consider...
// code here runs **first**
gameScore.saveInBackground(new SaveCallback() {
public void done(ParseException e) {
// code here runs **third, much later than second**
if (e == null) {
objectId = gameScore.getObjectId();
} else {
Log.e("saveInBackground", getErrorMessage(e));
}
}
// code here runs **second, immediately**
Run the "get" query within the completion handler of the save and you'll see that it works. (Of course, there's not much reason to get the object since you have the handle to the object upon which you just invoked save).

Getting null value of Global variable in java class?

Here is my Code:
public class ServerCall {
Context context;
public int cartCount;
public ServerCall(Context context){
this.context=context;
}
public Integer addCartItem(RequestObject requestObject) {
new AddToCartList().execute(requestObject);
Log.d("count",String.valueOf(cartCount));
return cartCount;
}
public class AddToCartList extends AsyncTask<RequestObject, Void, JSONObject> {
#Override
protected JSONObject doInBackground(RequestObject... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(arg0[0], ServiceHandler.POST);
// List<Products> result = new ArrayList<Products>();
Log.d("Response: ", "> " + jsonStr);
JSONObject product = new JSONObject();
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
product = jsonObj.getJSONObject("rsBody");
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return product;
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
try {
if (result != null) {
String status = result.getString("status");
int totalCartItem = result.getInt("totalCartItem");
/* cartHelper = new CartHelper();
cartHelper.setStatus(status);
cartHelper.setTotalCartItem(totalCartItem);*/
cartCount=totalCartItem;
Log.d("status",status);
Log.d("totalCartItem",String.valueOf(cartCount));
Toast.makeText(context, status, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
return;
}
}
}
We didn't get value of global variable cartCount which I set inside AddToCartList class and try to get its value from addCartItem() function from where AddToCartList is called but we get null value.
I think that the main problem in your solution is the fact that you're trying to edit ServerCall variable from an Inner class, this would work only if cartCount is static, and I suggest you wait for your task to be finished as some people have already mentioned, using the get method new AddToCartList().execute().get()
The problem is, ServerCall and AddToCartList are not the same class, so you must first get a reference to the servercall in addtocartlit, then reference the cartCount using your reference to the servercall instance, like call.cartCount, instead of cartcount, unless its an inner class which it does not appear to be.
Secondly, you must save a reference to the addtocartlist asynctask inside addCartItem() ,then call its .get() method after starting it, this will ensure it finishes before you try to log the new value.

Parse object try/catch exception error

I am trying to get a list of values from parse.com for a specific object, however i seem to be struggling with one error that keeps coming up on my screen which doesn't seem to be wrong, unless it is related to some other issue that i may have missed. i have initialised my aF variable as List aF; as you cannot see it in this class. the error i am getting is on aF = query.find() where it says unhandled exceptions,
protected Void doInBackground(Void... params) {
// Locate the class table named "UploadedFiles" in Parse.com
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("UploadedFiles");
query.orderByDescending("_created_at");
try {
Toast.makeText(getActivity(), "Success",
Toast.LENGTH_LONG).show();
aF = query.find();
} catch (ParseException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
I also tried to implement an if statement exception rule, but it also gives me errors in which i thought i shouldn't use it, as i cannot implement a return statement with this case.
public void done(ParseException e) {
if (e == null) {
aF = query.find()
Toast.makeText(getActivity(), "Success",
Toast.LENGTH_LONG).show();
} else {
Log.d("Error", e.toString());
}
}
});
EDIT
protected Void doInBackground(Void... params) {
// Locate the class table named "UploadedFiles" in Parse.com
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("UploadedFiles");
query.orderByDescending("_created_at");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, com.parse.ParseException e) {
try {
aF = query.find();
} catch (ParseException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
}
});
return null;
}
Thank you for all answers, I am getting now a new error saying that variable query is accessed from within inner class, needs to be declared final. does that mean i have to set it as a return statement ?
You have use like this.
Use callback FindCallback
Retrieves a list of ParseObjects that satisfy this query from the
source in a background thread.
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> arg0, ParseException arg1) {
// TODO Auto-generated method stub
}
});

Assigning an object from Parse.Query to a global variable

I'm trying to access a variable inside a query from parse but it gets destroyed when the query finishes.
As you can see in the code below, I output it into the console and it does work, but if I try to assign it to a variable and then use it it returns null. Any help would be appreciated.
ParseQuery<ParseObject> query = ParseQuery.getQuery("Hospitales");
query.whereEqualTo("Codigo", id);
query.getFirstInBackground(new GetCallback<ParseObject>() {
public void done(ParseObject object, ParseException e) {
if (object == null) {
Log.d("score", "The getFirst request failed.");
} else {
Log.d("id", "Retrieved the object.");
String status = object.getString("Hospital");
m2Status = object.getString("Hospital");
System.out.println("Hospital: " + status);
System.out.println(status + m2Status);
}
}
});
So, basically, your problem seems to be that you're running an asynchronous query and trying to access the variable before that query has returned.
Here's how you could set up your code to defer using the variable until you can be reasonably sure you have a value to actually use:
private void runQuery() {
ParseQuery<ParseObject> query = ParseQuery.getQuery("Hospitales");
query.whereEqualTo("Codigo", id);
query.getFirstInBackground(new GetCallback<ParseObject>() {
public void done(ParseObject object, ParseException e) {
if (object == null) {
Log.d("score", "The getFirst request failed.");
// You don't have a good value to use, so figure
// out a way to handle that scenario
} else {
Log.d("id", "Retrieved the object.");
String status = object.getString("Hospital");
m2Status = object.getString("Hospital");
System.out.println("Hospital: " + status);
System.out.println(status + m2Status);
// You have a good value to use, so
// now you can actually use it
afterQueryProcessing();
}
}
});
}
private void afterQueryProcessing() {
// You can access m2Status here reliably,
// assuming you only call this method
// as shown above, but you should still
// use defensive programming
if (m2Status != null) {
// Now you know you have a value to use...
}
}

Categories

Resources