ConfirmationActivity wearable how to? - java

I have a problem with the implementation ConfirmationActivity. When I downloaded the full API reference documentation, and looked the part about ConfirmationActivity, I saw only one method onCreate and do not understand how to implement animation like in demos. When I search in sdk/templates/ I don't find any. Help me please.
There is my code:
public class MyActivity extends Activity {
public static final String EXTRA_TITLE = "title";
public static final String EXTRA_TEXT = "text";
#Override
public void onResume() {
super.onResume();
setContentView(R.layout.activity_my);
setTitle(getTextExtra(EXTRA_TITLE, "Title"));
((TextView)findViewById(R.id.text)).setText(getTextExtra(EXTRA_TEXT, "text"));
findViewById(R.id.ok).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
}
private String getTextExtra(String extra, String def) {
final String text = getIntent().getStringExtra(extra);
if (text == null) {
return def;
} else {
return text;
}
}
}

Like this one
public static void showSuccessActivity(Context context) {
Intent intent = new Intent(context, ConfirmationActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(ConfirmationActivity.EXTRA_ANIMATION_TYPE, ConfirmationActivity.SUCCESS_ANIMATION);
context.startActivity(intent);
}

Related

How can disable hardware HomeKey and BackKey and Recent Butoom in Android Programitcaly

I'm setting a new app and want to disable hardware key like home,back and recent key in my app. I found some code in stackoverflow but none of them work.
Is it possible to disable hardware key?
public class MainActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
}
public void onAttachedToWindow() {
this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG);
KeyguardManager keyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
KeyguardManager.KeyguardLock lock = keyguardManager.newKeyguardLock(KEYGUARD_SERVICE);
lock.disableKeyguard();
}
}
do nothing in onBackPressed()
#Override
public void onBackPressed() {
}
add this in manifest
<uses-permission android:name="android.permission.REORDER_TASKS" />
and add this in onPause()
#Override
protected void onPause() {
super.onPause();
ActivityManager activityManager = (ActivityManager) getApplicationContext()
.getSystemService(Context.ACTIVITY_SERVICE);
activityManager.moveTaskToFront(getTaskId(), 0);
}
In your MainActivity -
#Override
public void onBackPressed() {
// super.onBackPressed(); commented this line in order to disable back press
//Write your code here
Toast.makeText(getApplicationContext(), "Back press disabled!", Toast.LENGTH_SHORT).show();
}
You can not block Recent and Home but you can restart activity if user click on Home.
Here is example
HomeWatcher Class
public class HomeWatcher {
static final String TAG = "hg";
private Context mContext;
private IntentFilter mFilter;
private OnHomePressedListener mListener;
private InnerRecevier mRecevier;
public HomeWatcher(Context context) {
mContext = context;
mFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
}
public void setOnHomePressedListener(OnHomePressedListener listener) {
mListener = listener;
mRecevier = new InnerRecevier();
}
public void startWatch() {
if (mRecevier != null) {
mContext.registerReceiver(mRecevier, mFilter);
}
}
public void stopWatch() {
if (mRecevier != null) {
mContext.unregisterReceiver(mRecevier);
}
}
class InnerRecevier extends BroadcastReceiver {
final String SYSTEM_DIALOG_REASON_KEY = "reason";
final String SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS = "globalactions";
final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";
final String SYSTEM_DIALOG_REASON_LONG_PRESS = "assist";
final String SYSTEM_DIALOG_REASON_VOICE_INTERACTION = "voiceinteraction";
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
if (reason != null) {
Log.e(TAG, "action:" + action + ",reason:" + reason);
if (mListener != null) {
if (reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) {
mListener.onHomePressed();
} else if (reason.equals(SYSTEM_DIALOG_REASON_RECENT_APPS)) {
mListener.onHomeLongPressed();
} else if (reason.equals(SYSTEM_DIALOG_REASON_LONG_PRESS)) {
mListener.onHomeLongPressed();
} else if (reason.equals(SYSTEM_DIALOG_REASON_VOICE_INTERACTION)) {
mListener.onHomeLongPressed();
}
}
}
}
}
}
OnHomePressedListener interface
public interface OnHomePressedListener {
void onHomePressed();
void onHomeLongPressed();
}
In Your Main Activity
HomeWatcher mHomeWatcher = new HomeWatcher(this);
mHomeWatcher.setOnHomePressedListener(new OnHomePressedListener() {
#Override
public void onHomePressed() {
Log.d("Pressed", "Home Button Pressed");
}
#Override
public void onHomeLongPressed() {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
Log.d("LongPressed", "Home Long Button Pressed");
}
});
mHomeWatcher.startWatch();

Passing an object from the 2nd activity back to main activity using serializable in android

The first block of code below is my main activity in which I created the intent to the second activity. On this activity I am displaying the expense in a list view which for now I have left out as it is not fully implemented. What I simple want to do is launch the second activity and let the user enter in details and press a button to add the activity to the list view.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.addExpense) {
Intent intent = new Intent(this, ExpenseActivity.class);
startActivityForResult(intent, 1);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// check that it is the SecondActivity with an OK result
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
Expense expense = (Expense) data.getSerializableExtra("sampleObject");
Expenses.add(expense);
}
}
}
final Button btnAddExpense = (Button) findViewById(R.id.btnAddExpense);
btnAddExpense.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String amountV = txtAmountVat.getText().toString();
int amountVTwo = Integer.parseInt(amountV);
String amountI = txtAmount.getText().toString();
int amountITwo = Integer.parseInt(amountI);
Expense expense = new Expense(amountITwo, amountVTwo, txtDateOfExpense.getText().toString(), txtDateAdded.getText().toString(), datePaid, paid, txtDes.getText().toString(), imageUri );
Intent intent = new Intent();
intent.putExtra("Expense", expense);
setResult(MainActivity.RESULT_OK, intent);
finish();
}
});
And this is my second activity in which the user enters in data. When i try pass back the expense object the emulator states the app has stopped working. Please could I have some help as I don't know what is causing this problem. This is what my class looks like.
public class Expense implements Serializable {
private int _amount, _amountVat;
private String _dateOfExpense, _dateAdded, _datePaid, _expenseDescription;
private Boolean _paid;
private Uri _imageUri;
public Expense(int amount, int amountVat, String dateOfExpense, String dateAdded, String datePaid, Boolean paid, String expenseDescription, Uri imageUri){
_amount = amount;
_amountVat = amountVat;
_dateOfExpense = dateOfExpense;
_dateAdded = dateAdded;
_datePaid = datePaid;
_paid = paid;
_expenseDescription = expenseDescription;
_imageUri = imageUri;
}
public int get_amount() {
return _amount;
}
public void set_amount(int _amount) {
this._amount = _amount;
}
public int get_amountVat() {
return _amountVat;
}
public void set_amountVat(int _amountVat) {
this._amountVat = _amountVat;
}
public String get_dateOfExpense() {
return _dateOfExpense;
}
public void set_dateOfExpense(String _dateOfExpense) {
this._dateOfExpense = _dateOfExpense;
}
public String get_dateAdded() {
return _dateAdded;
}
public void set_dateAdded(String _dateAdded) {
this._dateAdded = _dateAdded;
}
public String get_datePaid() {
return _datePaid;
}
public void set_datePaid(String _datePaid) {
this._datePaid = _datePaid;
}
public Boolean get_paid() {
return _paid;
}
public void set_paid(Boolean _paid) {
this._paid = _paid;
}
public Uri get_imageUri() {
return _imageUri;
}
public void set_imageUri(Uri _imageUri) {
this._imageUri = _imageUri;
}
public String get_expenseDescription() {return _expenseDescription;}
public void set_expenseDescription(String _expenseDescription) {this._expenseDescription = _expenseDescription;}
}
Much can't be said about your problem without proper log details.
But you can go through these points.
The problem with Serializable approach is that reflection is used and it is a slow process. This method create a lot of temporary objects and cause quite a bit of garbage collection. So, it might be due to this. Try running on a real device & see if it persists.
Alternatively, you can implement Parcelable to your class which is faster than Serializable.

How to get data from getter setter class?

I am beginner in android development , I have some issue please help me.
I have 2 screen Login and After Login , I have set User id in login class and i want to use that user_id in after login how to get , when I use get method find Null how to resolve this problem.
here is my Login Code`public class LoginActivity extends FragmentActivity {
private EditText userName;
private EditText password;
private TextView forgotPassword;
private TextView backToHome;
private Button login;
private CallbackManager callbackManager;
private ReferanceWapper referanceWapper;
private LoginBean loginBean;
Context context;
String regid;
GoogleCloudMessaging gcm;
String SENDER_ID = "918285686540";
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
static final String TAG = "GCM";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_login);
Utility.setStatusBarColor(this, R.color.tranparentColor);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/OpenSans_Regular.ttf");
setupUI(findViewById(R.id.parentEdit));
userName = (EditText) findViewById(R.id.userName);
userName.setTypeface(tf);
userName.setFocusable(false);
userName.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View view, MotionEvent paramMotionEvent) {
userName.setFocusableInTouchMode(true);
Utility.hideSoftKeyboard(LoginActivity.this);
return false;
}
});
password = (EditText) findViewById(R.id.passwordEText);
password.setTypeface(tf);
password.setFocusable(false);
password.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View paramView, MotionEvent paramMotionEvent) {
password.setFocusableInTouchMode(true);
Utility.hideSoftKeyboard(LoginActivity.this);
return false;
}
});
forgotPassword = (TextView) findViewById(R.id.forgotPassword);
forgotPassword.setTypeface(tf);
forgotPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),ForgotPasswordActivity.class);
startActivity(intent);
}
});
backToHome = (TextView) findViewById(R.id.fromLogToHome);
backToHome.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
login = (Button) findViewById(R.id.loginBtn);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doLoginTask();
// Intent intent = new Intent(getApplicationContext(), AfterLoginActivity.class);
// startActivity(intent);
}
});
}
private void doLoginTask() {
String strEmail = userName.getText().toString();
String strPassword = password.getText().toString();
if (strEmail.length() == 0) {
userName.setError("Email Not Valid");
} else if (!Utility.isEmailValid(strEmail.trim())) {
userName.setError("Email Not Valid");
} else if (strPassword.length() == 0) {
password.setError(getString(R.string.password_empty));
} else {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject();
jsonObject.putOpt(Constants.USER_NAME, strEmail);
jsonObject.putOpt(Constants.USER_PASSWORD, strPassword);
jsonObject.putOpt(Constants.DEVICE_TOKEN, "11");
jsonObject.putOpt(Constants.MAC_ADDRESS, "111");
jsonObject.putOpt(Constants.GPS_LATITUDE, "1111");
jsonObject.putOpt(Constants.GPS_LONGITUDE, "11111");
} catch (JSONException e) {
e.printStackTrace();
}
final ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();
CustomJSONObjectRequest jsonObjectRequest = new CustomJSONObjectRequest(Request.Method.POST, Constants.USER_LOGIN_URL, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
pDialog.dismiss();
Log.e("LoginPage", "OnResponse =" + response.toString());
getLogin(response);
//LoginBean lb = new LoginBean();
//Toast.makeText(getApplicationContext(),lb.getFull_name()+"Login Successfuly",Toast.LENGTH_LONG).show();
Intent intent = new Intent(getApplicationContext(),AfterLoginActivity.class);
startActivity(intent);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"Something, wrong please try again",Toast.LENGTH_LONG).show();
pDialog.dismiss();
}
});
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Log.e("LoginPage", "Url= " + Constants.USER_LOGIN_URL + " PostObject = " + jsonObject.toString());
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
}
}
public void getLogin(JSONObject response) {
LoginBean loginBean = new LoginBean();
if (response != null){
try {
JSONObject jsonObject = response.getJSONObject("data");
loginBean.setUser_id(jsonObject.getString("user_id"));
loginBean.setFull_name(jsonObject.getString("full_name"));
loginBean.setDisplay_name(jsonObject.getString("display_name"));
loginBean.setUser_image(jsonObject.getString("user_image"));
loginBean.setGender(jsonObject.getString("gender"));
loginBean.setAuthorization_key(jsonObject.getString("authorization_key"));
} catch (JSONException e) {
e.printStackTrace();
}
}
Toast.makeText(getApplicationContext(),"User id is "+loginBean.getUser_id(),Toast.LENGTH_LONG).show();
}
public void onBackPressed() {
finish();
}
public void setupUI(View view) {
//Set up touch listener for non-text box views to hide keyboard.
if (!(view instanceof EditText)) {
view.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
Utility.hideSoftKeyboard(LoginActivity.this);
return false;
}
});
}
}
}
`
here is my AfterLogin class`public class AfterLoginActivity extends FragmentActivity {
private ImageView partyIcon;
private ImageView dealIcon;
private ImageView deliveryIcon;
private TextView txtParty;
private TextView txtDeals;
private TextView txtDelivery;
boolean doubleBackToExitPressedOnce = false;
int backButtonCount = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_after_login);
Utility.setStatusBarColor(this, R.color.splash_status_color);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
partyIcon = (ImageView)findViewById(R.id.party_Icon);
dealIcon = (ImageView)findViewById(R.id.deals_Icon);
deliveryIcon = (ImageView)findViewById(R.id.delivery_Icon);
partyIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplication(), BookPartyActivity.class);
startActivity(intent);
}
});
dealIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplication(), DealsActivity.class);
startActivity(intent);
}
});
deliveryIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LoginBean loginBean = new LoginBean();
Toast.makeText(getBaseContext(),"Auth"+loginBean.getUser_id(),Toast.LENGTH_LONG).show();
Intent intent = new Intent(getApplicationContext(),MyAuction.class);
startActivity(intent);
}
});
}
/*
public void onBackPressed()
{
if (doubleBackToExitPressedOnce)
{
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
doubleBackToExitPressedOnce = true;
Toast.makeText(this, "you have logged in ,plz enjoy the party", Toast.LENGTH_LONG).show();
new Handler().postDelayed(new Runnable()
{
public void run()
{
doubleBackToExitPressedOnce = false;
}
}
, 2000L);
}*/
#Override
public void onBackPressed()
{
if(backButtonCount >= 1)
{
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
else
{
Toast.makeText(this, "Press the back button once again to close the application.", Toast.LENGTH_SHORT).show();
backButtonCount++;
}
}
}`
here is LoginBean`public class LoginBean {
private String user_id;
private String full_name;
private String display_name;
private String user_image;
private String gender;
private String authorization_key;
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getUser_id() {
return user_id;
}
public void setFull_name(String full_name) {
this.full_name = full_name;
}
public String getFull_name() {
return full_name;
}
public void setDisplay_name(String display_name) {
this.display_name = display_name;
}
public String getDisplay_name() {
return display_name;
}
public void setUser_image(String user_image) {
this.user_image = user_image;
}
public String getUser_image() {
return user_image;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getGender() {
return gender;
}
public void setAuthorization_key(String authorization_key) {
this.authorization_key = authorization_key;
}
public String getAuthorization_key() {
return authorization_key;
}
}`
//in your both activity or create class
private SharedPreferences mSharedPreferences;
//in your login on getLogin() method ;
mSharedPreferences = getSharedPreferences("user_preference",Context.MODE_PRIVATE);
//save actual drawable id in this way.
if(mSharedPreferences==null)
return;
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putInt("userId", loginBean.getUser_id());
editor.commit();
// in your after login acvtivity on deliverable method
private SharedPreferences mSharedPreferences;
mSharedPreferences = getSharedPreferences("user_preference",Context.MODE_PRIVATE);
if(mSharedPreferences==null)
return;
string userId = mSharedPreferences.getString("userId", "");
You can write and apply below mentioned steps (Please ignore any syntactical error, I am giving you simple logical steps).
step 1 - Make a global application level loginObject setter and getter like below. Make sure to define Application class in your manifest just like you do it for your LoginActivity
public class ApplicationClass extends Application{
private LoginBean loginObject;
public void setLoginBean(LoginBean object) {
this.loginObject = object;
}
public LoginBean getName() {
return this.loginObject
}
}
Step - 2 Get an instance of ApplicationClass object reference in LoginActivity to set this global loginObject
e.g. setLogin object in your current Loginactivity like this
......
private ApplicationClass appObject;
......
#Override
protected void onCreate(Bundle savedInstanceState) {
......
appObject = (ApplicationClass) LoginActivity.this.getApplication();
.......
appObject.setLoginBean(loginObject)
}
Step - 3 Get an instance of ApplicationClass object reference in any other Activity get this global loginObject where you need to access this login data.
e.g. getLogin object in your otherActivity like this
......
private ApplicationClass appObject;
......
#Override
protected void onCreate(Bundle savedInstanceState) {
......
appObject = (ApplicationClass) LoginActivity.this.getApplication();
.......
LoginBean loginObject = appObject.getLoginBean();
}

starting activity from a callback method

i use a class WebServiceAdapter using volley library for implementing http connections. since i can't find a way to return a string to activity
i use an interface to callnback into MainActivity. in it i want to start a new activity but it is not starting
my WebServiceAdapterClass
public WebServiceAdapter(Context context){
this.context = context;
status = "new";
rQueue = Volley.newRequestQueue(context);
}
private WebServiceInterface wsi;
public void sendGetRequest(String page,Map<String,String> map, WebServiceInterface i){
wsi = i;
String query = "";
if(!map.isEmpty()){
for (Map.Entry<String, String> entry : map.entrySet())
{
query =query + entry.getKey()+"="+entry.getValue()+'&';
}
}
if(query.length() != 0)
query = query.substring(0,query.length()-1);
StringRequest sRequest = new StringRequest(Request.Method.GET,BASE_URI+page+"?"+query,
new Response.Listener<String>() {
#Override
public void onResponse(String response){
wsi.successCallback(response,context);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error){
wsi.errorCallback("failed",context);
}
});
rQueue.add(sRequest);
}
and in MainActivity inside callBack which use an interface for callback
#Override
public void successCallback(String s, Context c) {
Intent myintent = new Intent(c,VerifyRegister.class);
startActivity(myintent);
finish();
}
but the activity is not starting
i tried passing this , getApplicationContext() and Main Activity.this instead of c. but never worked
what i wanted was return a string on success i cant find another way
but the new activity is not starting
update
code of verifyRegister class
public class VerifyRegister extends Activity implements WebServiceInterface{
private Button verifyButton;
private EditText loginVerify;
StorageAdapter sAdapter;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
sAdapter = new StorageAdapter();
if(sAdapter.getValue(this, "phone").length() == 0)
finish();
setContentView(R.layout.login_verify);
verifyButton = (Button) findViewById(R.id.verifyButton);
loginVerify = (EditText) findViewById(R.id.loginVerify);
verifyButton.setOnClickListener(new OnClickListener(){
public void onClick(View v){
}
});
}
#Override
public void successCallback(String s, Context c) {
// TODO Auto-generated method stub
}
#Override
public void errorCallback(String s, Context c) {
// TODO Auto-generated method stub
}
*update 2 *
i called the WebService Adapter like this
wAdaptor = new WebServiceAdapter(this);
wAdaptor.sendGetRequest("/register",new HashMap<String,String> (),this);
Please verify that your VerifyRegister class does in fact extends Activity. And if it does extends, please make sure that you have added it in AndroidManifest file.
One more thing you can try is, you can write it like this:
Intent myintent = new Intent(MainActivity.this,VerifyRegister.class);
Try this:
#Override
public void successCallback(String s, Context c) {
Intent myintent = new Intent(MainActivity.this,VerifyRegister.class);
c.startActivity(myintent);
//finish(); Dont use this
}
New activity starts with Context, I your case you should call it by using to activity currently running.
MainActivity.this.startActivity(anyintent);
i searched similar projects in github
and found this
public void successCallback(String s, Context c) {
Intent myintent = new Intent(MainActivity.this,VerifyRegister.class);
MainActivity.this.startActivity(myintent);
finish()
}

Passing Parcelable Object between Intents

I am having an issue passing an object I have created in between events. I used the website http://www.parcelabler.com/ to create the parcelable element of the code. The object class is show below: (The Item class is another simple object containing Strings and doubles and has also been made parcelable)
import android.os.Parcel;
import android.os.Parcelable;
import java.util.ArrayList;
public class Diner implements Parcelable {
private String name;
private ArrayList<Item> itemList = new ArrayList<Item>();
public Diner(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void addItem(Item foodItem) {
itemList.add(foodItem);
foodItem.incrementBuyerCount();
}
public double getPrice() {
double total = 0;
for(Item item : itemList) {
total += item.getPrice() / item.getBuyerCount();
}
return total;
}
protected Diner(Parcel in) {
name = in.readString();
if (in.readByte() == 0x01) {
itemList = new ArrayList<Item>();
in.readList(itemList, Item.class.getClassLoader());
} else {
itemList = null;
}
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
if (itemList == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeList(itemList);
}
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<Diner> CREATOR = new Parcelable.Creator<Diner>() {
#Override
public Diner createFromParcel(Parcel in) {
return new Diner(in);
}
#Override
public Diner[] newArray(int size) {
return new Diner[size];
}
};
}
In my main activity, I have a button which opens an 'Add Diner' activity, when a button is pressed and waits for a result.
private final int SET_REQUEST = 1;
addDinerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), AddDinerActivity.class);
startActivityForResult(intent, SET_REQUEST);
}
});
The Add Diner activity is opened, the user enters a String in a Diner Name EditText which is used the create a new Diner object and returns to the main activity when an OK button is pressed.
okButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = getIntent();
Diner newDiner = new Diner(dinerNameEditText.getText().toString());
intent.putExtra("newDiner", newDiner);
setResult(RESULT_OK, intent);
finish();
}
});
Finally the Diner object is received and added to an array in the main activity:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == RESULT_OK) {
if(requestCode == SET_REQUEST) {
Diner newDiner = getIntent().getParcelableExtra("newDiner");
dinerList.add(newDiner);
}
}
}
Unfortunately my code is crashing when I try to save the Diner object and pass it to the main activity, can anyone see why this is?
Use data third parameter of onActivityResult method instead of getIntent() for getting data from Intent which is sent from Activity which is started using startActivityForResult :
Diner newDiner = data.getParcelableExtra("newDiner");

Categories

Resources