I tried to put if else inside the button onClick
Here's the onClick
#Override
public void onClick(View view) {
ettext.getText().toString();
viewword.getText().toString();
select();
if(viewword.equals("")) {
Toast.makeText(getBaseContext(), "Does not exist in database.1", Toast.LENGTH_LONG).show();
}else{
sendChatMessage();
}
}
Here's the onPostExecute
#Override
protected void onPostExecute(String result) {
TextView disp = (TextView) findViewById(R.id.view);
try {
JSONObject json_data = new JSONObject(result);
word = json_data.getString("server_response");
disp.setText(word);
} catch (JSONException e) {
disp.setText("");
}
}
The problem is that the app is not reading the if else statement and proceed to onPostExecute. My solution was to create a method inside the onPostExecute but I don't know how.
The problem here isn't onPostExecute but your code.
viewword.getText().toString();
This is just a String value and you need to store it in some variable when you are checking if it is null or not. Hence your code should be either
String checkVariable =viewword.getText().toString();
if(checkVariable.equals(""){
\\your code}
or
if(viewword.getText().toString().equals("")
Hope this helps :)
You can't create a method in a method, you can create a method in the AsyncTask class and call it in onPostExecute method.
Related
I have created two class one is LoginSignupActivity.java and another is ProfileActivity.java
LoginSignUpActivity.java---
public class LoginSignupActivity extends AppCompatActivity {
** static string id; **
public void getUserDetailsFromFB() {
GraphRequest request = GraphRequest.newMeRequest(
AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(final JSONObject object, GraphResponse response) {
try{
** id=response.getJSONObject().getString("id");**
}
catch (JSONException e) {
//If anything goes wrong
Log.e("my",e.toString());
}
})
}
}
}
ProfileActivity.java ---
public class ProfileActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
ImageView imageView = (ImageView) findViewById(R.id.dp);
if(imageView!=null){
** String fbid = (new LoginSignupActivity).getUserDetailsFromFB().id; **
if(fbid!=null){
Glide.with(this).load("http://graph.facebook.com/1615242245409408/picture?type=large").into(imageView);
//Glide.with(this).load("http://graph.facebook.com/" + "1675239799409652" + "/picture?type=large").into(imageView);
Log.d("mayank", LoginSignupActivity.id);
}
else{
Log.d("mayank","null facebook id");
}
}
else {
Log.d("mayank","null image view");
}
}
}
When I access id inside ProfileActivity.java
it shows null value.
I want to access that value that is obtained inside LoginSignupActivity.java.
Please help.
Thanks
Try to make id public and I think you should get it throw LoginSignUpActivity.id
If the login is for one time only I recommand you to use SharedPreference.
do as:
public static String id="NA";
Use String instead of string.
Android Studio "cannot resolve symbol String"
List item
you will get NA if id is not received by your line of code:
id=response.getJSONObject().getString("id");
As you told in comment, you should use the value of id after getting it only
id=response.getJSONObject().getString("id");
I thing you should only start the ProfileActivity.java just after getting id valueas below:
id=response.getJSONObject().getString("id");
Intent intent=new Intent(LoginSignupActivity.this,ProfileActivity.class);
startActivity(intent);
Thanks
I'm currently working on a android app in which I use asynctasks to carry out json rest request. I've got this working fine. I have also got a progress dialog being made visible on the preexecute then dismissing it on the postexecute all working fine. see code below.
#Override
protected void onPreExecute(){
Variables var = Variables.getInstance();
Variables.getInstance().showPd(ProgressDialog.show(Variables.getInstance().getContext(), var.getValue("loggingin_text"), var.getValue("pleasewait"), true, false));
}
protected void onPostExecute( JSONObject[] loginresponse ){
Variables.getInstance().dismisspd();
try {
JSONObject responseheader = loginresponse[0].getJSONObject("commonInputParameters");
if (responseheader.getString("status").equals("SUCCESS")) {
Variables.getInstance().setUsername( loginresponse[1].getString("username") );
Variables.getInstance().setSessiontoken(responseheader.getString("userSessionToken"));
delegate.onRequestCompletion( true );
} else {
delegate.onRequestCompletion(false);
}
}catch (JSONException je ) {
this.cancel( true );
}
}
final Button _loginBTN = ( Button ) findViewById(R.id.loginBTN );
_loginBTN.setText( vars.getValue( "loginbtn_text" ) );
_loginBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Functions functions = Functions.getInstance();
if( functions.isNetworkAvailable(getApplicationContext())) {
if (functions.fullypopulated(new Object[]{_username, _password})) {
LoginRequest login = new LoginRequest(new responseInterface() {
#Override
public void onRequestCompletion(boolean successfulRequest) {
Variables.getInstance().dismisspd();
if ( !successfulRequest ) {
functions.showDialog(Variables.getInstance().getValue("login_err"), findViewById(R.id.input_username));
functions.clearEditText(new EditText[]{_username, _password});
functions.setError(new EditText[]{_username, _password});
} else {
Intent intent = new Intent(getApplicationContext(), NavigationHandler.class);
startActivity(intent);
finish();
}
}
#Override
public void onRequestCompletion(String requestResponse) {}
#Override
public void onRequestCompletion(int requestResponse) {}
#Override
public void onRequestCompletion(float requestResponse) {}
});
Map<String, String> loginDetails = new HashMap<String, String>();
loginDetails.put("username", _username.getText().toString());
loginDetails.put("password", _password.getText().toString());
login.execute(loginDetails);
} else {
functions.showDialog(Variables.getInstance().getValue("no_details"), findViewById(R.id.input_username));
functions.clearEditText(new EditText[]{_username, _password});
functions.setError(new EditText[]{_username, _password});
}
}
else {
functions.showDialog(Variables.getInstance().getValue("no_network"), findViewById(R.id.input_username));
}
}
});
The problem is that when I try to work in a time out into the async task the progress dialog shows but not until after it has completed and at which point I can't remove it.
This is how I'm trying to run it with a time out.
try{
login.execute(loginDetails).get( 5000, TimeUnit.MILLISECONDS );
}catch (InterruptedException ie ){
}catch (ExecutionException ee){
}catch (TimeoutException te ){
login.cancel(true);
}
Yes I know the catches are empty right now.
UPDATE:
Never mind looking at the get function again, it actually blocks the UI thread that is why the Progress Dialog isn't showing until the ASyncTask has completed. Is there anyway to implement a timeout feature?
Cancelling a task
A task can be cancelled at any time by invoking cancel(boolean). Invoking this method will cause subsequent calls to isCancelled() to return true. After invoking this method, onCancelled(Object), instead of onPostExecute(Object) will be invoked after doInBackground(Object[]) returns.
From http://developer.android.com/reference/android/os/AsyncTask.html
Mind the bold pieces ... as to my understanding, you should dismiss the Dialog in onCancelled() in case of Timeout.
Basically, what I want to do is to create Aztec code reader plugin.
So I need to open some kind of camera screen inside my app. I should do that inside my Java code, which right now looks like so:
public class AztecReaderPlugin extends CordovaPlugin {
#Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
try {
if(action.equals("open")) {
Context context = cordova.getActivity().getApplicationContext();
Intent intent = new Intent(context, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
callbackContext.success();
return true;
}
callbackContext.error("Something gone wrong!");
return false;
} catch (Exception e) {
callbackContext.error(e.getMessage());
return false;
}
}
}
It basically should execute the code inside MainActivity class. And the MainActivity class method onCreate looks like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_main);
Button btnDoFocus = (Button)findViewById(R.id.buttonAutoFocus);
btnDoFocus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
preview.autoFocus();
}
});
Button btnDoAztec = (Button)findViewById(R.id.buttonDoAztec);
btnDoAztec.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
preview.setEnableReadAztecCode(true);
}
});
}
The thing is, when I did forget about AztecReaderPlugin, and run the MainActivity code as an standalone Android app, it works just like I would want.
I can't find any tutorial/post that would help me with my problem, and I don't have time to learn Android developing.
So my question is: How can I include that Aztec Code Reader inside my Cordova App?
// EDIT
I can Include my Plugin into App, the problem lays inside AztecReaderPlugin class and some Activity-related method. My problem is I can't open some kind of camera view through cordova. And that Camera view is my Plugin.
Sure you can
Firstly you need to declare your custom plugin in config.xml. You can found this file in res > xml folder.
<feature name="CustomPlugin">
<param name="android-package" value="com.Phonegap.CustomPlugin" />
</feature>
Then you need to implement plugin by using Java- code
public class CustomPlugin extends CordovaPlugin {
#Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext)
throws JSONException {
if (action.equals("sayHello")){
try {
String responseText = "Hello world, " + args.getString(0);
callbackContext.success(responseText);
} catch (JSONException e){
callbackContext.error("Failed to parse parameters");
}
return true;
}
return false;
}
}
Finally we calling a plugin from javascript
function initial(){
var name = $("#NameInput").val();
cordova.exec(sayHelloSuccess, sayHelloFailure, "CustomPlugin", "sayHello", [name]);
}
function sayHelloSuccess(data){
alert("OK: " + data);
}
function sayHelloFailure(data){
alert("FAIL: " + data);
}
I am very confused, i am trying for two days to make animation on an image while my engine is thinking of a move (this is a game app). I execute the chooseMove() method inside AsyncTask object because it is a little heavy recursive function that may take some time,and also i want to rotate an hourglass image while the engine is thinking. and i tried to do it every way i know: another AsyncTask, Android's own animation class,handlers etc'. but no matter what i do it seems that i can't make it work. if i try to execute two threads at the same time,it only executes one of them, and the same thing happens with android own animation class. so i tried to use a progress dialog just to see that i am not getting crazy,and guess what.. same problem! I show the progress dialog in the onPreExecute() ,but the doInBackgroun() never gets done! the progress dialog take control over the whole app for some reason. how should i do it? i though that the progress dialog is meant for this kind of things. thx!
EDIT: this is the code of my async task class. as you can see, i am showing a progress dialog in the onPreExecute() ,and dismissing it in the onPostExecute. but the onPost never gets called because the doInBackground() never gets called either.
protected void onPreExecute() {
super.onPreExecute();
activity.setPlaying(true);
if (android.os.Build.VERSION.SDK_INT >android.os.Build.VERSION_CODES.GINGERBREAD) {
// only for gingerbread and newer versions
activity.invalidateOptionsMenu();
}
progressDialog = new ProgressDialog(activity);
progressDialog.setMessage("Thinking...");
progressDialog.setIndeterminate(true);
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
}
#Override
protected Integer doInBackground(Void... arg0) {
int engineWin = board.takeWin(board.getBoard(), engine.getNumberOfEngine());
int opponentWin = board.takeWin(board.getBoard(), engine.getNumberOfOpponent());
if(engineWin!=-1){
try{
Thread.sleep(500);
}
catch(Exception e){}
return engineWin;
}
else if(opponentWin!=-1){
try{
Thread.sleep(500);
}
catch(Exception e){}
return opponentWin;
}
else{
if(engine.isEnginesTurn()&&!Board.checkGameOver(board.getBoard())){
int[] newBoard = new int[42];
System.arraycopy(board.getBoard(), 0, newBoard, 0, 42);
return engine.chooseMove(engine.isEnginesTurn(),newBoard,-500001,500001,0,4).getMove();
}
else{
return -1;
}
}
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
progressDialog.dismiss();
if(result!=-1){
ballAnimTask = new BallAnimTask(activity,boardView,board,engine);
ballAnimTask.execute(findSlotNumberByIndex(result));
}
}
this is the recursive chooseMove() i am calling in doInBackground(). before i tried to show the progress dialog,everything worked just fine. there is no problem with this function or any other function for that matter. only when i tried to do animations or dialogs at the same time,i got issues. the chooseMove() is physically on another class and i am only calling it from the AsyncTask. maybe this is the problem??
public Best chooseMove(boolean side,int[]board,int alpha,int beta,int depth,int maxDepth){
Best myBest = new Best();
Best reply;
int num;
if(Board.checkGameOver(board)||depth==maxDepth){
myBest.setScore(returnPositionScore(board));
return myBest;
}
if(side){
myBest.setScore(alpha);
num = numberOfEngine;
}
else{
myBest.setScore(beta);
num = numberOfOpponent;
}
ArrayList<Integer> availableMoves = new ArrayList<Integer>();
availableMoves = searchAvailableMoves(board);
for(int move:availableMoves){
board[move] = num;
reply = chooseMove(!side,board,alpha,beta,depth+1,maxDepth);
board[move] = 0;
if(side&&reply.getScore()>myBest.getScore()){
myBest.setMove(move);
myBest.setScore(reply.getScore());
alpha = reply.getScore();
}
else if(!side&&reply.getScore()<myBest.getScore()){
myBest.setMove(move);
myBest.setScore(reply.getScore());
beta = reply.getScore();
}
if(alpha>=beta){
return myBest;
}
}
return myBest;
}
If you want to perform any UI related operation from within an AsyncTask you need to call the AsyncTask publishProgress method. This will invoke an onProgressUpdate callback in the main UI thread and so you can then safely perform your UI related operations there.
Obviously any code in the onProgressUpdate can't block, though, since you are now back in the main UI thread. But you can update a status bar, for example, and then wait for the next onProgressUpdate callback before you update it again.
Just for some inspiration, here is the general code format that I have used successfully to show a horizontal progress bar which updates while a background task is running. I know it doesn't answer your exact question, but I hope it helps you to find your solution.
ProgressDialog myProgressDialog;
private void someFunctionThatStartsTheAsyncTask()
{
new myBackgroundTask.execute(someIntegerArgument);
}
private class myBackgroundTask extends AsyncTask<Integer, Integer, Boolean>
{
protected void onPreExecute()
{
myProgressDialog = new ProgressDialog(myContext);
myProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
myProgressDialog.setTitle("Doing something in background...");
myProgressDialog.setMessage("Please wait...");
myProgressDialog.setCancelable(false);
myProgressDialog.setIndeterminate(false);
myProgressDialog.setMax(100);
myProgressDialog.setProgress(0);
myProgressDialog.show();
}
protected Boolean doInBackground(Integer... params)
{
int someVariable = params[0];
boolean success;
for (whatever loop conditions)
{
// some long-running stuff, setting 'success' at some point
...
publishProgress(newPositionForProgressBar);
}
return success;
}
protected void onProgressUpdate(Integer... progressPosition)
{
myProgressDialog.setProgress(progressPosition[0]);
}
protected void onPostExecute(Boolean result)
{
myProgressDialog.dismiss();
if (result)
{
//doInBackground returned true
}
else
{
//doInBackground returned false
}
}
}
I have placed the parse method inside onCreate method. But my problem is how to show the Android Loading... Dialog??
Parse.initialize(this, "a", "b");
ParseQuery query = new ParseQuery("Category");
query.findInBackground(new FindCallback() {
#Override
public void done(List<ParseObject> catObjects, ParseException arg1) {
Log.d("Catlength", String.valueOf(catObjects.size()));
for(int i =0; i<catObjects.size(); i++){
Log.d("lengthName"+String.valueOf(i), String.valueOf(catObjects.get(i).getInt("Id")));
Category category = new Category();
category.Name= catObjects.get(i).getString("CatName");
category.id= catObjects.get(i).getInt("Id");
categories.add(category);
}
if(categories.size()>0){
setListAdapter(new CategoryArrayAdapter(CategoryListActivity.this, R.layout.row_category, categories));
}
else{
Toast.makeText(CategoryListActivity.this, "Our servers are busy. Hit refresh..", 3000).show();
}
}
});
Everything works fine in the above code but I couldn't figure out how to show the Dialog.
I'm unable to use AsycTask also as parse sdk invokes its own thread in the background and before the findInBackground execution finishes, the doInBackground completes the Asyc thread. That's why I invoked it in the main thread.
As the result I always get no results in my ArrayList.
Can someone please enlighten me.
I was in the same situation regarding the progress dialog, tried a few tricks and finally just declared a ProgressDialog class member:
protected ProgressDialog proDialog;
then created two methods:
protected void startLoading() {
proDialog = new ProgressDialog(this);
proDialog.setMessage("loading...");
proDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
proDialog.setCancelable(false);
proDialog.show();
}
protected void stopLoading() {
proDialog.dismiss();
proDialog = null;
}
and called startLoading() before the background operation and stopLoading()
inside the background operation after I got the the results.
startLoading();
ParseUser.logInInBackground(userName.getText().toString(), hashedPass, new LogInCallback() {
public void done(ParseUser user, ParseException e) {
if (user != null) {
Log.d(Constants.TAG, "User Loged in.");
ParseManager.sCurrentUser = user;
stopLoading();
finish();
} else {
stopLoading();
invalidCreds();
}
}
});
if you want to use AsyncTask don't call findInBackground() you can use find().
you can check it out in the api https://parse.com/docs/android/api/com/parse/ParseQuery.html#find()
hope this helps.
It's easy to get the progress of both uploads and downloads using ParseFile by passing a ProgressCallback to saveInBackground and getDataInBackground. For example:
byte[] data = "Working at Parse is great!".getBytes();
ParseFile file = new ParseFile("resume.txt", data);
file.saveInBackground(new SaveCallback() {
public void done(ParseException e) {
// Handle success or failure here ...
}
}, new ProgressCallback() {
public void done(Integer percentDone) {
// Update your progress spinner here. percentDone will be between 0 and 100.
}
});