Go to another activity after click on button - Android - android

I have this onClickListener method on my login activity in my android app:
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(txtEmail.getWindowToken(), 0);
imm.hideSoftInputFromWindow(txtPassword.getWindowToken(), 0);
String password = txtPassword.getText().toString();
String email = txtEmail.getText().toString();
if ((txtEmail.length() == 0) || (txtPassword.length() == 0)) {
Toast.makeText(LoginMember.this, "You need to provide values for Email and Password", Toast.LENGTH_SHORT).show();
return;
}
//Go ahead and perform the transaction
String[] params = {email,password};
new EndpointsAsyncTaskInsert(LoginMember.this).execute(params);
}
});
It sends data to Google App Engine without any problems, already my EndpointsAsyncTask class defined, etc etc
Now, my problem is, I need to also go to another activity after this, I'm not realyl sure, but If I remember well I could do this automatically when logged in by using SQLite, don't know how to accomplish it here.
Already have the activities I need declared on manifest.
It should be something like this:
#Override
public void onClick(View v){
Intent intent = new Intent(LoginMember.this, WelcomeScreen.class);
startActivity(intent);
}
My problem is that I don't know how to "add" or "append" this activity transaction into this logic, I'm fairly new to android and google app engine, Any ideas???
Thanks in advance!
EDIT
This is my EndpointsAsyncTaskInsert code:
package com.kkoci.shairlook;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import com.appspot.shairlook1.userEndpoint.UserEndpoint;
import com.appspot.shairlook1.userEndpoint.model.User;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.extensions.android.json.AndroidJsonFactory;
import com.google.api.client.googleapis.services.AbstractGoogleClientRequest;
import com.google.api.client.googleapis.services.GoogleClientRequestInitializer;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
/**
* Created by kristian on 04/07/2015.
*/
public class EndpointsAsyncTaskInsert extends AsyncTask<String, Void, User> implements GoogleClientRequestInitializer {
private static UserEndpoint myApiService = null;
private Context context;
EndpointsAsyncTaskInsert(Context context) {
this.context = context;
}
#Override
public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
// put it here no in MyClass
abstractGoogleClientRequest.setDisableGZipContent(true);
}
// class MyClass{} // you don't need it
#Override
protected User doInBackground(String... params) {
User response = null;
if (myApiService == null) { // Only do this once
UserEndpoint.Builder builder = new UserEndpoint.Builder(AndroidHttp.newCompatibleTransport(),
new AndroidJsonFactory(), null)
// options for running against local devappserver
// - 10.0.2.2 is localhost's IP address in Android emulator
// - turn off compression when running against local devappserver
.setRootUrl("https://shairlook1.appspot.com/_ah/api/")
.setGoogleClientRequestInitializer(this);
// end options for devappserver
myApiService = builder.build();
}
try {
User users = new User();
users.setEmail(params[0]);
users.setPassword(params[1]);
users.setName(params[2]);
response = myApiService.insertUser(users).execute();
} catch (Exception e) {
Log.d("Could not Add User", e.getMessage(), e);
}
return response;
}
}
SECOND EDIT
This is how it looks right now, it's giving me 'java.lang.NoClassDefFoundError' on this line: new EndpointsAsyncTaskInsert(LoginMember.this) {
:
public class LoginMember extends Activity {
private static
//DbAdapter dbAdapter = null;
//EditText txtUserName;
EditText txtPassword;
EditText txtEmail;
Button btnLogin;
TextView Forgot_text;
Button twitter;
Button facebook;
//Button btnRegister;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
txtPassword = (EditText) findViewById(R.id.et_pw);
txtEmail = (EditText) findViewById(R.id.et_email);
btnLogin = (Button) findViewById(R.id.btn_login);
twitter = (Button) findViewById(R.id.twitter);
facebook = (Button) findViewById(R.id.facebook);
Forgot_text = (TextView) findViewById(R.id.Forgot_text);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(txtEmail.getWindowToken(), 0);
imm.hideSoftInputFromWindow(txtPassword.getWindowToken(), 0);
String password = txtPassword.getText().toString();
String email = txtEmail.getText().toString();
if ((txtEmail.length() == 0) || (txtPassword.length() == 0)) {
Toast.makeText(LoginMember.this, "You need to provide values for Email and Password", Toast.LENGTH_SHORT).show();
return;
}
//Go ahead and perform the transaction
String[] params = {email,password};
//new EndpointsAsyncTaskInsert(LoginMember.this).execute(params);
/**try{ Intent k = new Intent(LoginMember.this, WelcomeScreen.class);
startActivity(k);
}catch(Exception e){
}**/
new EndpointsAsyncTaskInsert(LoginMember.this) {
protected void onPostExecute(User result) {
super.onPostExecute(result);
// Do something with result
Intent intent = new Intent(LoginMember.this, WelcomeScreen.class);
startActivity(intent);
}
}.execute(params);
}
});
}
public void getUser(View v) {
new EndpointsAsyncTask(this).execute();
}
public void insertUser(View v) {
new EndpointsAsyncTaskInsert(this).execute();
}
}

ok, i see, maybe you should do this, i haven't tryied this yet, but could help you:
Before onCreate method, declare a var of this way:
Activity currentActivity;
then inside onCreate method do this:
currentActivity=this;
so then, when you make you Asyctask, make this:
new EndpointsAsyncTaskInsert(currentActivity.getApplicationContext()).execute(params);
Hope that helps, let's me know if was helpFull, if not i try to help you in another way.
Regards.

In EndpointsAsyncTask class there should be method named onPostExecute() which is executed when your async task is completed. This is the place where you should notify your activity to go to another activity.
There are numerous way to do that.
You can create an Interface class for instance
public interface OnTaskFinishListener{
void onFinish();
}
and then implement this interface in your caller class:
public class YourActivity extends Activity implements OnTaskFinishListener {
void onFinish(){
Intent intent = new Intent(LoginMember.this, WelcomeScreen.class);
startActivity(intent);
}
}
When you create asynctask you should pass this reference as a parameter in its constructor and keep it in task fields and when the task is done call the onFinish method.
public EndpointsAsyncTaskInsert extends AsyncTask...{
private OnTaskFinishListener listener;
public EndpointsAsyncTaskInsert(OnTaskFinishListener listener){
this.listener = listener;
}
protected void onPostExecute(..){
//notify the listener
listener.onFinish();
}
}
Second and more loosely coupled way is to use an event bus library, for example, greenrobots EventBus https://github.com/greenrobot/EventBus, then you can post an event when your task is finished, and then you can receive that event in your activity without setting up any listeners.

You can make an anonymous version of your AsyncTask class and override the onPostExecute to start the new activity after it is done.
new EndpointsAsyncTaskInsert(LoginMember.this) {
protected void onPostExecute(User result) {
super.onPostExecute(result);
// Do something with result
Intent intent = new Intent(LoginMember.this, WelcomeScreen.class);
startActivity(intent);
}
}.execute(params);

Maybe this might work
if ((txtEmail.length() == 0) || (txtPassword.length() == 0)) {
Toast.makeText(LoginMember.this, "You need to provide values for Email and Password", Toast.LENGTH_SHORT).show();
return;
}
else{
String[] params = {email,password};
new EndpointsAsyncTaskInsert(LoginMember.this).execute(params);
}
In the class which extends the Asynctask override the onpostexecute method and add the following code
Intent in=new Intent(Login.this,Welcome.class);
in.putExtra("email",email);
in.putExtra("password",password);
startActivity(in);
You can use bundle to send data from one activity to another and retrieve from the bundle in the Welcome activity
Intent in=getIntent();
String email=in.getStringExtra("email");

Related

Callbacks in Android

I am new to Android and programming as a whole and I need a little help with callbacks. I understand the gist of callbacks but I am unsure of how to go about implementing.
Context: I am writing a simple notetaking app that allows the user to write text and saving it to the app. The user can then request to read the file with a button. The text is then displayed on a textview in the main activity. There is an option to wipe this file and this is done with a confirmation pop up, which is another activity. This pop up contains 2 buttons, one to cancel and one to wipe. If the file is not empty it will wipe and does nothing if empty. I am not sure if this is the best way to implement it but I want to use the wipe button to callback to the main activity to clear the textview. The way I was thinking of was by using the callback to send a boolean value back. The main activity will check if the boolean is true and clear the textview if it is. I am unsure of how to implement the callback in my popup display to send this boolean value back to the main activity.
Code for main activity
public class MainActivity extends AppCompatActivity implements Popout.ClearTextView {
Button bnRead,bnWrite,bnClear;
TextView tvFileOP;
EditText etInput;
// private static final String INPUT_CONTENT = "inputContent";
public static final String TV_CONTENT = "textViewContent";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bnRead = (Button) findViewById(R.id.bnRead);
bnWrite = (Button) findViewById(R.id.bnWrite);
bnClear = (Button) findViewById(R.id.bnClear);
tvFileOP = (TextView) findViewById(R.id.tvFileOP);
etInput = (EditText) findViewById(R.id.etInput);
tvFileOP.setMovementMethod(new ScrollingMovementMethod());
final String fileName = "test_file";
String data;
bnRead.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
FileInputStream fIn = openFileInput(fileName);
int c;
String temp = "";
while ( (c=fIn.read()) != -1){
temp = temp + Character.toString((char) c);
}
tvFileOP.setText(temp);
Toast.makeText(getBaseContext(),"file successfully read", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
});
bnWrite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String data = etInput.getText().toString();
try {
FileOutputStream fOut = openFileOutput(fileName,MODE_APPEND);
fOut.write(data.getBytes());
fOut.close();
etInput.setText("");
Toast.makeText(getBaseContext(),"file successfully written", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
});
bnClear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this,Popout.class));
}
});
}
#Override
protected void onSaveInstanceState(#NonNull Bundle outState) {
outState.putString(TV_CONTENT,tvFileOP.getText().toString());
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(#NonNull Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
tvFileOP.setText(savedInstanceState.getString(TV_CONTENT));
}
#Override
public void clearTextView(Boolean clear) {
if (clear){
tvFileOP.setText("");
}
}
}
Code for popup confirmation menu
public class Popout extends AppCompatActivity {
Button bnClosepopup,bnWipe;
TextView tvConfirmation;
String fileName = "test_file";
TextView tvFileOP;
public interface ClearTextView {
public void clearTextView(Boolean clear);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.popupwindow);
bnClosepopup = (Button) findViewById(R.id.bnClosepopup);
bnWipe = (Button) findViewById(R.id.bnWipe);
tvConfirmation = (TextView) findViewById(R.id.tvConfirmation);
//HIDING THE TOOL BAR AT THE TOP OF THE SCREEN
this.getSupportActionBar().hide();
//GETTING THE SIZE OF THE SCREEN
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int height = displayMetrics.heightPixels;
int width = displayMetrics.widthPixels;
getWindow().setLayout((int) (width*0.8) , (int) (0.8*height));
bnClosepopup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
bnWipe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
File dir = getFilesDir();
File file = new File(dir, fileName);
boolean deleted = file.delete();
Toast.makeText(getBaseContext(),"file has been deleted",Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
finish();
}
});
}
}
I am very new to android development and any tips on how to improve my code would be greatly appreciated :)
In this case there is no way to pass the interface to the other activity, because this is an activity to activity communication.
You have to use some other method, there is multiple ways to approach, the best way I can think of is to use startActivityForResult() to start the activity and then wait for a response to come back, and then query this response in the MainActivity by overriding the onActivityResult() method:
Example
In the MainActivity:
//on click of this button
bnClear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,Popout.class);
int requestCode = 12; //it could be whatever you want
startActivityForResult(intent , requestCode);
}
});
//override this method
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//this is triggered when you finish the Popout Activity
if(requestCode == 12 && resultCode == Activity.RESULT_OK){
// get the boolean data returned from the Popout Activity
boolean deleted = data.getBooleanExtra("deleted_state" , false); //false is default if no value exists
}
}
In the Popout activity:
bnWipe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
File dir = getFilesDir();
File file = new File(dir, fileName);
boolean deleted = file.delete();
//send the result to onActivtyResult() in MainActivity
Intent result = new Intent();
result.putExtra("deleted_state", deleted );
setResult(Activity.RESULT_OK, result);
Toast.makeText(getBaseContext(),"file has been deleted",Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
finish();
}
});
UPDATE:
It will be like this:
// get the boolean data returned from the Popout Activity
boolean deleted = data.getBooleanExtra("deleted_state" , false);
if (deleted){
tvFileOP.setText("");
}
..........
As far as what if Understood your problem correctly: You want to control your 'Wipe' button click event from your activity. Here is the solution which may help you.
1: Make an overridden constructor of your dialog class.
2: Create one abstract method in the dialog class. (say - onWipeButtonClick)
You need to make your dialog class abstract as well.
3: Inside on Click Listener of 'Wipe' button, call onWipeButtonClick abstract method.
4: Create the instance of dialog in the main activity where ever you want. The compiler will give you an error because you haven't implemented the call back method.
do implement your onWipeButtonClick method and do needful for wipe data inside the method.
public abstract class WipeDialog extends Dialog{
private Context context;
public WipeDialog(Context context){
this.context = context;
}
public abstract void onWipeButtonClick(boolean isTextEmpty);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.<XML_FILE>);
<initialization>
btnWipe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onWipeButtonClick(<YOUR_BOOLEAN_CHECK>);
}
});
}
}
And now in Activity:
WipeDialog dialog = new WipeDialog(MainActivity.this) {
#Override
public void onWipeButtonClick(boolean isTextEmpty) {
//Do Need full with respected to your requirement on click of button 'WIPE'
}
};
Hope this will help.
Thanks!

Async task not populating list properly

I'm developing a feed app, where people can make posts and these posts will populate a RecyclerView.
I have a FAB button that leads to a post activity, but when I post and then comeback to the MainActivity the list is not updated. But when I use the logout button and log back in, the list gets updated, or when I launch the activity it works.
I think this happens because my Async function gets called to work on onCreate, but I can't work like these, I need the AsyncTask to automatically fetch, otherwise people won't get the list updated in real time.
Could you please show me a light in the dark? Here are the codes for MainActivity, PostActivity and logout function from another class.
Main Activity:
public class MainActivity extends AppCompatActivity {
private AppCompatActivity activity = MainActivity.this;
private RecyclerView recyclerViewNews;
private List<Noticia> listNoticias;
private NewsRecyclerAdapter newsRecyclerAdapter;
private DBNoticias databaseHelper;
private Button btnLogout;
private LinearLayoutManager mLayoutManager;
UserSession userSession;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userSession = new UserSession(getApplicationContext());
recyclerViewNews = findViewById(R.id.recyclerViewNews);
btnLogout = findViewById(R.id.btlogout);
TextView usuario = findViewById(R.id.textView5);
/**
* Olá mundo by Alciomar
*/
SharedPreferences sharedPreferences = getSharedPreferences("Reg", Context.MODE_PRIVATE);
String uName = sharedPreferences.getString("Name", "");
usuario.setText(uName.toUpperCase());
try {
btnLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
userSession.logoutUser();
}
});
} catch (Exception e) {
e.printStackTrace();
}
initStuff();
getDataFromPostgres();
FloatingActionButton fab = findViewById(R.id.fabNews);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, PostNews.class);
startActivity(intent);
}
});
}
/**
* This method is to initialize objects to be used
*/
private void initStuff() {
try {
listNoticias = new ArrayList<>();
newsRecyclerAdapter = new NewsRecyclerAdapter(listNoticias);
mLayoutManager = new LinearLayoutManager(getApplicationContext());
mLayoutManager.setReverseLayout(true);
mLayoutManager.setStackFromEnd(true);
recyclerViewNews.setLayoutManager(mLayoutManager);
recyclerViewNews.setItemAnimator(new DefaultItemAnimator());
recyclerViewNews.setHasFixedSize(true);
recyclerViewNews.setAdapter(newsRecyclerAdapter);
databaseHelper = new DBNoticias(activity);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* This method is to fetch all user records from SQLite
*/
private void getDataFromPostgres() {
// AsyncTask is used that SQLite operation not blocks the UI Thread.
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
listNoticias.clear();
for (DBNoticias dbNoticias : databaseHelper.getNewsList()) {
Noticia noticia = new Noticia();
noticia.setUser_id(dbNoticias.getId());
noticia.setNewsTitle(dbNoticias.getNewsTitle());
noticia.setNewsMessage(dbNoticias.getNewsPost());
listNoticias.add(noticia);
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
newsRecyclerAdapter.notifyDataSetChanged();
}
}.execute();
}
Post News Activity:
public class PostNews extends AppCompatActivity {
private DBNoticias dbNoticias;
private Button btnpostar;
private EditText editTextCDNewsTitle;
private EditText editTextCDNewsPost;
private Noticia noticia;
private SharedPreferences sharedPreferences;
public void alert(String titulo, String txt){
AlertDialog alertDialog = new AlertDialog.Builder(PostNews.this).create();
alertDialog.setTitle(titulo);
alertDialog.setMessage(txt);
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post_news);
btnpostar = findViewById(R.id.btn_postar);
dbNoticias = new DBNoticias();
editTextCDNewsTitle = findViewById(R.id.EditTextNewsTitle);
editTextCDNewsPost = findViewById(R.id.EditTextNewsPost);
}
public void salvarNoticia(View view) {
try {
{
String newsTitle = editTextCDNewsTitle.getText().toString();
String newsPost = editTextCDNewsPost.getText().toString();
if (!(editTextCDNewsTitle.getText().toString().equals("") || editTextCDNewsTitle.getText() == null ||
editTextCDNewsPost.getText().toString().equals("") || editTextCDNewsPost.getText() == null
)) {
sharedPreferences = getSharedPreferences("Reg", Context.MODE_PRIVATE);
String uName = sharedPreferences.getString("Name", "");
String uEmail = sharedPreferences.getString("Email", "");
int uIdUser = sharedPreferences.getInt("IdUser", 0);
dbNoticias.setNewsTitle(newsTitle);
dbNoticias.setNewsPost(newsPost);
dbNoticias.setIdUser(uIdUser);
dbNoticias.salvar();
noticia = new Noticia();
Toast.makeText(getApplicationContext(), "Notícia postada com sucesso",
Toast.LENGTH_LONG).show();
editTextCDNewsTitle.setText("");
editTextCDNewsPost.setText("");
}
}
}
catch (Exception e){
alert("Erro", e.getMessage());
}
}
Thank you in advance if you read and try to help!
There are multiple ways to do this:
Method 1 – Use onResume()
If you call your getDataFromPostgres() method in onResume instead of onCreate, it'll fetch data and refresh list every time the activity wakes from a pause (for example coming back from another activity)
// existing code
#Override
public void onResume(){
super.onResume();
getDataFromPostgres()
}
(This would be the simplest solution)
Method 2 – Poll the DB continuously
If there are other services that might be updating the database and you need to always show the latest state in the activity, another way (although really inefficient) would be to keep refreshing the list after a defined time period (let's say 10 seconds as an example).
How to run an async task for every x mins in android?
Method 3 – Use onActivityResult
If you want to update the list only when a new entry has been created in the second activity, you can use onActivityResult to notify the first activity on action and then refresh your list there.
How to manage `startActivityForResult` on Android?
Please use this, it's working for me
newsRecyclerAdapter.notifyItemInserted(position);
newsRecyclerAdapter.notifyDataSetChanged();

Android: How to implement Asynctask correctly for this below class?

Below is a login activity which connects with the server to perform login operation, so for this to do in Background thread how to use Asynctask's methods correctly?
I am new to android and not used Asynctask before, but I have seen tutorials still couldn't do it myself
//public class LoginActivity extends AppCompatActivity extends Asynctask shows some error
Edit: error is here
//public class LoginActivity extends AsyncTask extends
AppCompatActivity{ ( { expected)
public class LoginActivity extends AppCompatActivity{
private TextView tvLFS, tvOr;
private Button btnLog;
private EditText etUn, etPw;
private static final String TAG = "LoginActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//remove action bar
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.hide();
}
//change font of the heading
tvLFS = (TextView) findViewById(R.id.tvHeadingLFS);
Typeface typeface =
Typeface.createFromAsset(getAssets(),
"fonts/futuramediumitalicbt.ttf");
tvLFS.setTypeface(typeface);
init();
}
private void init() {
tvLFS = (TextView) findViewById(R.id.tvHeadingLFS);
tvOr = (TextView) findViewById(R.id.tvOR_LOGIN_USING);
btnLog = (Button) findViewById(R.id.btnLogin);
etUn = (EditText) findViewById(R.id.etUName);
etPw = (EditText) findViewById(R.id.etPass);
/* SharedPreferences pref = getSharedPreferences("ActivityPREF",
Context.MODE_PRIVATE);
SharedPreferences.Editor edt = pref.edit();
edt.putBoolean("activity_executed", true);
edt.commit();*/
btnLog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
final String usname = etUn.getText().toString();
final String uspass = etPw.getText().toString();
final LoginRequest loginRequest = new LoginRequest();
loginRequest.setClientType("mobile");
loginRequest.setMsService("login");
loginRequest.setMsServiceType("user-management");
List<LoginRequest.MsDataLogin> msDataLogList = new
ArrayList<>();
LoginRequest.MsDataLogin msData =
loginRequest.getMsDAtaLoginInstance();
msData.setUserName(usname);
msData.setUserPass(uspass);
msDataLogList.add(msData);
loginRequest.setMsData(msDataLogList);
RestClient.getApiInterface().postData(loginRequest).enqueue(new
ResponseResolver<LoginResponse>(LoginActivity.this) {
#Override
public void success(LoginResponse loginResponse) {
if (loginResponse.getErrorCode().equals("0"))
{
Toast.makeText(LoginActivity.this,
"Logged-in successfully!!", Toast.LENGTH_SHORT).show();
Intent in = new
Intent(getApplicationContext(), MainActivity.class);
startActivity(in);
finish();
} else
if(loginResponse.getErrorCode().equals("1")){
Toast.makeText(LoginActivity.this, "No
account found!! Please register", Toast.LENGTH_LONG).show();
}
}
#Override
public void failure(APIError error) {
Log.d(TAG, "failure: error--
"+error.getMessage());
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
Based on you edit, you're trying to extend two classes? Well, (I think) that's not possible in Java ...
Back to your question about AsyncTask. AsynTask are made to make task outside de Main Thread/UI Thread, for some scenarios (Ex.: the basic, not lock the UI while doing some work), for that reason you can't interact with the UI in a AsyncTask or even mix both things (is possible in some cases, but not recommended).
So you need to extends AsyncTask in other class than your view/activity (another Class.java or nested/internal class), example below:
public class MyAsyncTask extends AsyncTask<ParameterType, ProgressType, ReturnType> {
//Example to demonstrate UI interation
private IView view;
public MyAsyncTask(IView view) {
this.view = view;
}
#Override
protected ReturnType doInBackground(ParameterType... params) {
// do and update the work
return new ReturnType(); // work is done, return the result
}
// Override this method if you need to do something after the AsyncTask has finished (based on the return). Here you can interact with the UI too.
#Override
protected void onPostExecute(ReturnType o) {
// Example of UI interaction
view.updateUI(o);
}
}
If you don't need Parameters, Returns or update the progress of your AsyncTask, you can use the 'Void' type in place ParameterType, ProgressType or ReturnType.
Then you can create a intance of MyAsyncTask in other classes (Ex.: your activity) an call ‘execute()’ method to start the AsyncTask.
public class Foobar extends AppCompatActivity implements IView {
... code ...
MyAsyncTask fooTask = new MyAsyncTask(this); // Foobar class needs to implement IView interface
fooTask.execute(parameters); // execute AsyncTask with 'parameters'
... code ...
}
Based on your code you're trying to make a Network call. So you need need migrate your network call to inside 'doInBackground' method, and call the next activity (or show the error) in the 'onPostExecute'.
I not very familiar with your implementation (RestClient, ResponseResolver), but I think you can use Retrofit/Jackson libraries for a more solid solution. They are not very difficult to understand and makes Network calls easier.
In the references below there are other alternatives that you can use instead of a AsyncTask.
Here is some references:
https://developer.android.com/reference/android/os/AsyncTask.html
https://developer.android.com/guide/components/processes-and-threads.html
Good coding.

Retrofit login button click not working with fragment

I have tried logging in with retrofit wherein the login button from activity login will redirect me to home activity if successful. Then I tried using fragments. I have two fragments on main activity that can replace each other which are login fragment and register fragment. Know, I know that if I want to use any of the fragment's elements, then I must implement an interface that the mainactivity must implement to be able to use let's say edittext, buttons from fragment. I have done this, but when I try to implement retrofit's asynchronous task in the login button method, when I click it, nothing is happening. I tried putting a toast in the same login button method and it works, but not the retrofit call.
Login fragment:
public class LoginLayout extends Fragment {
EditText schoolid;
EditText password;
Login login;
Button loginButton;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.login_layout, container, false);
schoolid = (EditText) view.findViewById(R.id.loginschoolid);
password = (EditText) view.findViewById(R.id.loginpassword);
loginButton = (Button) view.findViewById(R.id.login);
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String schoolidtext = schoolid.getText().toString();
String passwordtext = password.getText().toString();
login.loginButtonClicked(schoolidtext, passwordtext);
}
});
return view;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try{
login = (Login) activity;
}catch(Exception e) {
}
}
public interface Login{
public void loginButtonClicked(String schoolid, String password);
}
}
MainActivity:
public void loginUser(String schoolid, String password) {
//Here we will handle the http request to insert user to mysql db
//Creating a RestAdapter
RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint(ROOT_URL) //Setting the Root URL
.build(); //Finally building the adapter
//Creating object for our interface
LoginAPI api = adapter.create(LoginAPI.class);
api.loginUser(
//Passing the values
schoolid,
password,
//Creating an anonymous callback
new Callback<Response>() {
#Override
public void success(Response result, Response response) {
//On success we will read the server's output using bufferedreader
//Creating a bufferedreader object
BufferedReader reader = null;
//An string to store output from the server
String output = "";
//Initializing buffered reader
try {
reader = new BufferedReader(new InputStreamReader(result.getBody().in()));
//Reading the output in the string
output = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (output.equals("Successful")) {
isLoggedIn = true;
if(isLoggedIn == true) {
Intent i = new Intent(MainActivity.this, HomeActivity.class);
startActivity(i);
}
//Displaying the output as a toast
Toast.makeText(MainActivity.this, output, Toast.LENGTH_LONG).show();
}
}
#Override
public void failure(RetrofitError error) {
//If any error occured displaying the error as toast
Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
}
);
}
#Override
public void loginButtonClicked(String schoolid, String password) {
//this line doesn't work
loginUser(schoolid, password);
//this line works
Toast.makeText(MainActivity.this, "button clicked", Toast.LENGTH_LONG).show();
}
Fragments get attached to activity, the onFragmentInteraction is a call back method that your activity use to interact with the fragment
LoginFragment
Create a listener
private OnFragmentInteractionListener mListener;
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
void onLoginFragmentInteraction(String schoolidtext, String passwordtext);
}
Initialize the listener
#Override
public void onStart() {
super.onStart();
try {
mListener = (OnFragmentInteractionListener) getActivity();
} catch (ClassCastException e) {
throw new ClassCastException(getActivity().toString()
+ " must implement OnFragmentInteractionListener");
}
}
Call the listener
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String schoolidtext = schoolid.getText().toString();
String passwordtext = password.getText().toString();
//call the listenner on the main activity
mListener.onLoginFragmentInteraction(schoolidtext, passwordtext);
}
});
MainActivity
Implement the call back :
public class MainActivity extends Activity
implements LoginFragment.OnFragmentInteractionListener{
}
Override it
#Override
public void onLoginFragmentInteraction(String schoolidtext, String passwordtext) {
loginUser(schoolid, password);
Toast.makeText(MainActivity.this, "button clicked", Toast.LENGTH_LONG).show();
}

How to get data from other activity in android?

I have two activities such as Activity A and B and I'm trying to pass two different strings from A to B using Bundle and startActivity(intent).
Like that:
Intent intent = new Intent(A.this, B.class);
Bundle bundle = new Bundle();
bundle.putString("vidoedetails", filedetails);
//bundle.putString("videoname", filename);
intent.putExtras(bundle);
//intent.putExtra("videofilename", filename);
//intent.putExtra("vidoefiledetails", filedetails);
startActivity(intent);
And in class B I'm using two TextViews to display the strings from class A seperately.
Like that:
Intent i = getIntent();
Bundle extras = i.getExtras();
filedetails = extras.getString("videodetails");
filename = extras.getString("videoname");
The problem is filedetils get printed in class B but not the file name.
Any solution for this?
you have a typo:
bundle.putString("vidoedetails", filedetails);
should be
bundle.putString("videodetails", filedetails);
I know I am 9 days late on this answer, but this is a good example of why I create a constants class. With a constants class, it doesnt matter if it is misspelled ("video" -> "vidoe") because it will be 'misspelled' in both places as you are referencing it through a well known location.
Constants.java
public static String WELL_KNOWN_STRING "org.example.stackoverflow.4792829";
Activity1.java
bundle.putString(Constants.WELL_KNOWN_STRING, filedetails);
Activity2.java
filedetails = extras.getString(Constants.WELL_KNOWN_STRING);
Yes, you spelled wrongly videodetails:
Yours: vid*OE*details
Correct: vid*EO*details
// First activity
actvty_btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(v.getContext(),SECONDACTIVITY.class);
startActivityForResult(i, STATIC_INTEGER_VALUE);
}
});
/* This function gets the value from the other activity where we have passed a value on calling this activity */
public void activity_value() {
Intent i = getIntent();
Bundle extras=i.getExtras();
if(extras !=null) {
// This is necessary for the retrv_value
rtrv_value = extras.getString("key");
if(!(rtrv_value.isEmpty())) {
// It displays if the retrieved value is not equal to zero
myselection.setText("Your partner says = " + rtrv_value);
}
}
}
// Second activity
myBtn.setOnClickListener(new View.OnClickListener () {
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), FIRSTACTIVITY.class);
Bundle bundle = new Bundle();
bundle.putString("key", txt1.getText().toString());
// Here key is just the "Reference Name" and txt1 is the EditText value
intent.putExtras(bundle);
startActivity(intent);
}
});
Here's another way to pass data between Activities. This is just an example from a tutorial I was following. I have a splash screen that runs for 5 seconds and then it would kill the sound clip from:
#Override
protected void onPause() {
super.onPause();
ourSong.release();
}
I decided I wanted the sound clip to continue playing into the next activity while still being able to kill/release it from there, so I made the sound clip, MediaPlayer object, public and static, similar to how out in System.out is a public static object. Being new to Android dev but not new to Java dev, I did it this way.
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
public class Splash extends Activity {
public static MediaPlayer ourSong; // <----- Created the object to be shared
// this way
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
ourSong = MediaPlayer.create(Splash.this, R.raw.dubstep);
ourSong.start();
Thread timer = new Thread() {
public void run() {
try {
sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
Intent openStartingPoint = new Intent(
"expectusafterlun.ch.androidtutorial.MENU");
startActivity(openStartingPoint);
}
}
};
timer.start();
}
}
Then from the next activity, or any other activity, I could access that MediaPlayer object.
public class Menu extends ListActivity {
String activities[] = { "Count", "TextPlay", "Email", "Camera", "example4",
"example5", "example6" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(Menu.this,
android.R.layout.simple_expandable_list_item_1, activities));
}
#Override
protected void onPause() {
super.onPause();
Splash.ourSong.release(); // <----- Accessing data from another Activity
// here
}
}

Categories

Resources