applying onDestroy apps - java

I want to call a method onDestroy to make my apps whenever I kill it and when open the apps still shown the activity I want. But, when I'm applying the onDestroy still nothing happen and didn't show the activity I wanted. What I'm trying to do is make the apps still load the data. Tell me a way, to execute this method. I want to know every detail for my final project.
Here is my activity
public class ChooseJob extends AppCompatActivity {
public RecyclerView recyclerView;
public RecyclerView.LayoutManager layoutManager;
FirebaseRecyclerAdapter<BothJobs, OrderViewHolder> adapter;
private FirebaseDatabase database;
private DatabaseReference request;
private DatabaseReference history;
//string Intent
String cName;
String cPhone;
String idJob;
String cImage;
String cAirport;
String cAirlines;
String cLuggage;
String fDetail;
String currentTime;
String cPlace;
TextView orderLayout;
MaterialSpinner spinner;
TextView id;
APIService mService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choose_job);
mService = Common.getFCMService();
database = FirebaseDatabase.getInstance();
request = database.getReference("RequestDetail");
history = database.getReference("History");
recyclerView = findViewById(R.id.listOrders);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
callIntent();
if (getIntent() != null)
loadOrders();
}
#Override
protected void onDestroy() {
super.onDestroy();
callIntent();
if (getIntent() != null)
{
loadOrders();
} else {
Toast.makeText(this, "Nothing HAPPEN!!!", Toast.LENGTH_SHORT).show();
}
}
private void callIntent() {
Intent idJobCarrier = getIntent();
idJob = idJobCarrier.getStringExtra("id");
Intent phoneCarrier = getIntent();
cPhone = phoneCarrier.getStringExtra("carrierPhone");
Intent nameCarrier = getIntent();
cName = nameCarrier.getStringExtra("carrierName");
Intent imageCarrier = getIntent();
cImage = imageCarrier.getStringExtra("carrierImage");
Intent airportCarrier = getIntent();
cAirport = airportCarrier.getStringExtra("carrierAirport");
Intent airlinesCarrier = getIntent();
cAirlines = airlinesCarrier.getStringExtra("carrierAirlines");
Intent locationCarrier = getIntent();
cPlace = locationCarrier.getStringExtra("carrierLocation");
Intent luggageCarrier = getIntent();
cLuggage = luggageCarrier.getStringExtra("carrierLuggage");
Intent flightDetails = getIntent();
fDetail = flightDetails.getStringExtra("flightDetails");
Intent timeStampt = getIntent();
currentTime = timeStampt.getStringExtra("saveCurrentDate");
}
private void loadOrders() {
adapter = new FirebaseRecyclerAdapter<BothJobs, OrderViewHolder>(
BothJobs.class,
R.layout.ob_task,
OrderViewHolder.class,
request.orderByChild("placeSend").equalTo(cPlace)
) {
#Override
protected void populateViewHolder(OrderViewHolder viewHolder, BothJobs model, final int position) {
viewHolder.tvId.setText("ID : " + adapter.getRef(position).getKey());
viewHolder.tvName.setText("Company Name : " + model.getCompanyName());
viewHolder.tvStatus.setText("Status : " + Common.convertCodeToStatus(model.getStatus()));
viewHolder.tvLocation.setText("Location To send : " + model.getPlaceSend());
viewHolder.tvWeight.setText("Weight : " + model.getWeight());
viewHolder.btn_edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// showUpdateDialog(adapter.getRef(position).getKey(), adapter.getItem(position));
// Toast.makeText(ChooseJob.this, "OK BOS.. aku mau ni job", Toast.LENGTH_SHORT).show();
}
});
}
};
adapter.notifyDataSetChanged();
recyclerView.setAdapter(adapter);
}

Related

Passing database value to variable

I'm rarely ask on here, so first of all I'm sorry if my question is readable or not allowed here. So what I'm trying to do here is passing the username from LoginActivity into the player1 variable at HomeActivity . here's the code for the HomeActivity.java class
public class HomeActivity extends Activity {
TextView NameTxt;
TextView CoinTxt;
TextView GemTxt;
String p1name = player1.getName();
int p1coin = player1.getCoins();
int p1gem = player1.getGems();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_screen);
//////TV declare///////
NameTxt = (TextView)findViewById(R.id.playerName);
CoinTxt = (TextView)findViewById(R.id.cointxt);
GemTxt = (TextView)findViewById(R.id.gemtxt);
NameTxt.setText(p1name);
CoinTxt.setText("Coin: " +p1coin);
GemTxt.setText("Gem: " +p1gem);
}
}
And this is LoginActivity.class
public class LoginActivity extends Activity {
EditText edit1;
EditText edit2;
EditText edit3;
Button registerBtn;
Button loginBtn;
DatabaseHelper myDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Set fullscreen and no title//////////
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
///////////////////////////////////////
setContentView(R.layout.login_screen);
edit1 = (EditText)findViewById(R.id.editpname);
edit2 = (EditText)findViewById(R.id.editpemail);
edit3 = (EditText)findViewById(R.id.editppw);
registerBtn = (Button)findViewById(R.id.registerbtn);
loginBtn = (Button)findViewById(R.id.loginbtn);
myDb = new DatabaseHelper(this);
loginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (validate()) {
String Email = edit2.getText().toString();
String Password = edit3.getText().toString();
User currentUser = myDb.Authenticate(new User(null, null, Email, Password));
if (currentUser != null) {
System.out.println("Successfull");
Intent intent = new Intent(getApplicationContext(),HomeActivity.class);
startActivity(intent);
finish();
} else {
System.out.println("Unsuccessfull");
}
}
}
});
registerBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (validate()) {
String UserName = edit1.getText().toString();
String Email = edit2.getText().toString();
String Password = edit3.getText().toString();
if (!myDb.isEmailExists(Email)) {
myDb.addUser(player1);
public User player1 = new User(null, UserName, Email, Password);
}
}
}
});
}
public boolean validate() {
boolean valid = false;
String Email = edit2.getText().toString();
String Password = edit3.getText().toString();
if (!android.util.Patterns.EMAIL_ADDRESS.matcher(Email).matches()) {
valid = false;
edit2.setError("Please enter valid email!");
} else {
valid = true;
edit2.setError(null);
}
if (Password.isEmpty()) {
valid = false;
edit3.setError("Please enter valid password!");
} else {
if (Password.length() > 5) {
valid = true;
edit3.setError(null);
} else {
valid = false;
edit3.setError("Password is to short!");
}
}
return valid;
}
}
And I also have simple User.java class
String id;
String userName;
String email;
String password;
int coins;
int gems;
public User(String id, String userName, String email, String password) {
this.id = id;
this.email = email;
//And so on. Don't mind this
}
public String getName() {
return this.userName;
}
public int getCoins() {
return this.coins;
}
public int getGems() {
return this.gems;
}
And I write the short code , for the sake of readability.
I get an error on
myDb.addUser(player1);
And the one below it.
I'm just trying to make so that the player name equals to the value of Username on the database . and also the coins and gems too. Can you guys help me to get the idea how to pass the value? It tooks me whole 3days to figure a way to fix this. And it just blew my brain. So maybe you guys can help me
Ignoring the database stuff and assuming that LoginActivity is started from another activity (MainActivity) then you could adapt the following which passes the Username and UserId (ample to then get any additional data in the HomeActivity from the database).
So this when it starts immediately invokes the LoginActivity.
Clicking Login (mimics getting user and id from db) starts the HomeActivity passing the Username and userid via Intent Extras.
The HomeActivity displays the username and userid, and additionally a DONE button.
Clicking the DONE button returns back through the stack (skippng LoginActivity as that was finished) to the MainActivity which changes the TextView from Hello World to Welcome Back (not that you'd ever see Hello World).
MainActivity.java :-
public class MainActivity extends AppCompatActivity {
TextView mMessage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMessage = this.findViewById(R.id.message);
// Immediately start Login Activity
Intent i = new Intent(MainActivity.this,LoginActivity.class);
startActivity(i);
}
#Override
protected void onResume() {
super.onResume();
mMessage.setText("Welcome back");
}
}
LoginActivity.java :-
public class LoginActivity extends AppCompatActivity {
public static final String INTENTKEY_USERNAME = "IK_USERNAME";
public static final String INTENTKEY_USERID = "IK_USERID";
Button mloginbtn;
Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mContext = this;
mloginbtn = this.findViewById(R.id.loginbtn);
mloginbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(mContext,HomeActivity.class);
i.putExtra(INTENTKEY_USERNAME,"Fred");
i.putExtra(INTENTKEY_USERID,99L);
startActivity(i);
finish();
}
});
}
}
HomeActivity.java
public class HomeActivity extends AppCompatActivity {
TextView mUsername, muserid;
Button mDone;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
mUsername = this.findViewById(R.id.username);
muserid = this.findViewById(R.id.userid);
mDone = this.findViewById(R.id.done);
mDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
Intent i = this.getIntent();
mUsername.setText(i.getStringExtra(LoginActivity.INTENTKEY_USERNAME));
muserid.setText(String.valueOf(i.getLongExtra(LoginActivity.INTENTKEY_USERID,0)));
}
}
I'd do the following:
...
Intent intent = new Intent(getApplicationContext(),HomeActivity.class);
intent.putExtra("username", Bob)
startActivity(intent);
finish();
...
and then in home have:
Intent intent = getIntent();
String easyPuzzle = intent.getExtras().getString("username");

Payment to this merchant is not allowed (invalid clientid)

I integrated Paypal in my android app in sandbox mode and everything worked perfectly fine. Now I switched to live mode and changed the client ID in my app as well.
Now this error is displayed when I tried to make a test purchase:
"Payment to this merchant is not allowed (invalid clientid)"
I don't know what to do. I changed the client id in every place from the sandbox id to the live id.
My class where Paypal is initialized when click on a button:
public class EssenActivity extends AppCompatActivity {
private static final String TAG = "Log Essen Activity";
private String kochuiD, preis, preis_ohne_euro, AnfragePortionenS, ungefahreAnkunftS, preisRe;
private EditText anzahlPortionen;
private TextView ungefähreAnkunft;
private Button essenBesätigenBtn;
private FirebaseFirestore firebaseFirestore;
private TextView preisRechner;
private FirebaseAuth mAuth;
public static final int PAYPAL_REQUEST_CODE = 7171;
private static PayPalConfiguration config = new PayPalConfiguration()
.environment(PayPalConfiguration.ENVIRONMENT_SANDBOX)
.clientId(Config.PAYPAL_CLIENT_ID);
private String amount, amountOhneEuro;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_essen);
essenBesätigenBtn = findViewById(R.id.essenBestätigen);
essenBesätigenBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
processPayment();
}
}
}
private void processPayment() {
amount = preisRechner.getText().toString();
amountOhneEuro = amount.replace("€", "");
PayPalPayment payPalPayment = new PayPalPayment(new BigDecimal(String.valueOf(amountOhneEuro)), "EUR",
"Bezahle das Essen", PayPalPayment.PAYMENT_INTENT_SALE);
Intent intent = new Intent(EssenActivity.this, PaymentActivity.class);
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
intent.putExtra(PaymentActivity.EXTRA_PAYMENT, payPalPayment);
startActivityForResult(intent, PAYPAL_REQUEST_CODE);
}
#Override
//
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (requestCode == PAYPAL_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
PaymentConfirmation confirmation = data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
if (confirmation != null) {
try {
String paymentDetails = confirmation.toJSONObject().toString(4);
startActivity(new Intent(EssenActivity.this, PaymentDetails.class)
.putExtra("PaymentDetails", paymentDetails)
.putExtra("PaymentAmount", amountOhneEuro)
.putExtra("Koch Uid", kochuiD)
);
} catch (JSONException e) {
e.printStackTrace();
}
}
} else if (resultCode == Activity.RESULT_CANCELED) {
Log.d(TAG, "onActivityResult: wurde gecancelt");
}
} else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID)
Toast.makeText(EssenActivity.this, "Ungültig", Toast.LENGTH_SHORT).show();
}
#Override
public void onDestroy() {
EssenActivity.this.stopService(new Intent(EssenActivity.this, PayPalService.class));
super.onDestroy();
}
}
My Config class:
public class Config {
public static final String PAYPAL_CLIENT_ID ="MY CLIENT ID";
}
My Paymentdetails class:
public class PaymentDetails extends AppCompatActivity {
private static final String TAG = "PAYMENT";
private TextView txtid, txtAmount, txtStatus;
private FirebaseFirestore firebaseFirestore;
private FirebaseAuth mAuth;
private DocumentReference docIdRef;
private String kochUid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_payment_details);
txtid = findViewById(R.id.txtId);
txtAmount = findViewById(R.id.txtAmount);
txtStatus = findViewById(R.id.txtStatus);
Intent intent = getIntent();
try {
JSONObject jsonObject = new JSONObject(intent.getStringExtra("PaymentDetails"));
showDetails(jsonObject.getJSONObject("response"), intent.getStringExtra("PaymentAmount"));
} catch (JSONException e) {
e.printStackTrace();
}
}
private void showDetails(JSONObject response, String paymentAmount) {
try {
firebaseFirestore = FirebaseFirestore.getInstance();
mAuth = FirebaseAuth.getInstance();
String uid = mAuth.getCurrentUser().getUid();
if (response.getString("state").equals("approved")) {
DocumentReference documentReference = firebaseFirestore.collection("essen_aktiv_anfrage").document(uid);
Map<String, String> anfrageMap = new HashMap<>();
anfrageMap.put("Id", response.getString("id"));
anfrageMap.put("Status", response.getString("state"));
anfrageMap.put("Betrag", paymentAmount + "€");
//NEU
anfrageMap.put("Anfrage User", uid);
anfrageMap.put("Koch Uid", kochUid);
documentReference.set(anfrageMap, SetOptions.merge())
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Intent intent = new Intent(PaymentDetails.this, MainActivity.class);
intent.putExtra("Bezahlung war erfolgreich", "approved");
Toast.makeText(PaymentDetails.this, "Bezahlung war erfolgreich", Toast.LENGTH_SHORT).show();
startActivity(intent);
}
});
} else{
Toast.makeText(PaymentDetails.this, "Bezahlung war nicht erfolgreich", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Any help is appreciated. Thank you very much.
Authorization defaults to sandbox unless explicitly set to "live". It needs to be set within the PayPalConfiguration which is used in creation of the oAuth token, and the creation of the APIContext which is used to call the PayPal service.
I had been getting the same error within a live environment, despite it working in sandbox. It is therefore likely that you have missed something.
Change ENVIRONMENT_SANDBOX to ENVIRONMENT_PRODUCTION

How to restart Handler after changing data value?

Good morning StackOverFlow i'm having some issues with Handler i'm trying to start in the MainActivity my Client.java after 50 seconds and also send the message and stop the client and that's work but i have to reopen the connection on every change of ip_txt or term_txt in settings.java
(data is saved from a EditText to DB by clicking on a button )
here is my MainActivity :
public class MainActivity extends AppCompatActivity {
Server server;
Client client;
Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
new ConnectTask().execute("");
if (client != null) {
client.sendMessage("IP#" + ipp + " " + "N#" + trm);
}
if (client != null) {
client.stopClient();
}
}
};
settings Settings;
public static TextView terminale, indr, msg;
TextView log;
String ipp,trm;
DataBaseHandler myDB;
allert Allert;
SharedPreferences prefs;
String s1 = "GAB Tamagnini SRL © 2017 \n" +
"Via Beniamino Disraeli, 17,\n" +
"42124 Reggio Emilia \n" +
"Telefono: 0522 / 38 32 22 \n" +
"Fax: 0522 / 38 32 72 \n" +
"Partita IVA, Codice Fiscale \n" +
"Reg. Impr. di RE 00168780351 \n" +
"Cap. soc. € 50.000,00 i.v. \n" + "" +
"REA n. RE-107440 \n" +
"presso C.C.I.A.A. di Reggio Emilia";
ImageButton settings, helps, allerts, home;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Utils.darkenStatusBar(this, R.color.colorAccent);
server = new Server(this);
myDB = DataBaseHandler.getInstance(this);
msg = (TextView) findViewById(R.id.msg);
log = (TextView) findViewById(R.id.log_avviso);
settings = (ImageButton) findViewById(R.id.impo);
helps = (ImageButton) findViewById(R.id.aiut);
allerts = (ImageButton) findViewById(R.id.msge);
home = (ImageButton) findViewById(R.id.gab);
terminale = (TextView) findViewById(R.id.terminal);
indr = (TextView) findViewById(R.id.indr);
final Cursor cursor = myDB.fetchData();
if (cursor.moveToFirst()) {
do {
indr.setText(cursor.getString(1));
terminale.setText(cursor.getString(2));
Client.SERVER_IP = cursor.getString(1);
trm = cursor.getString(2);
} while (cursor.moveToNext());
}
WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
ipp = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
handler.postDelayed(runnable,5000);
cursor.close();
server.Parti();
home.setOnClickListener(new View.OnClickListener() {
int counter = 0;
#Override
public void onClick(View view) {
counter++;
if (counter == 10) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setCancelable(true);
builder.setMessage(s1);
builder.show();
counter = 0;
}
}
});
settings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent impostazioni = new Intent(getApplicationContext(), settingsLogin.class);
startActivity(impostazioni);
}
});
helps.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent pgHelp = new Intent(getApplicationContext(), help.class);
startActivity(pgHelp);
}
});
allerts.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Server.count = 0;
SharedPreferences prefs = getSharedPreferences("MY_DATA", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.clear();
editor.apply();
msg.setVisibility(View.INVISIBLE);
Intent pgAlert = new Intent(getApplicationContext(), allert.class);
startActivity(pgAlert);
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
server.onDestroy();
}
public class ConnectTask extends AsyncTask<String, String, Client> {
#Override
protected Client doInBackground(String... message) {
client = new Client(new Client.OnMessageReceived() {
#Override
public void messageReceived(String message) {
publishProgress(message);
}
});
client.run();
return null;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
Log.d("test", "response " + values[0]);
}
}
}
Here is my settings.java:
public class settings extends AppCompatActivity {
TextView indr;
Client client;
EditText ip_txt,term_txt;
ImageButton home;
Button save;
DataBaseHandler myDB;
MainActivity activity;
String ipp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myDB = DataBaseHandler.getInstance(this);
setContentView(R.layout.activity_settings);
Utils.darkenStatusBar(this, R.color.colorAccent);
home = (ImageButton) findViewById(R.id.stgbtn);
indr = (TextView) findViewById(R.id.ipp);
ip_txt = (EditText) findViewById(R.id.ip);
term_txt = (EditText) findViewById(R.id.nTermin);
save = (Button) findViewById(R.id.save);
Cursor cursor = myDB.fetchData();
if(cursor.moveToFirst()){
do {
ip_txt.setText(cursor.getString(1));
term_txt.setText(cursor.getString(2));
}while(cursor.moveToNext());
}
cursor.close();
AddData();
home.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
ipp = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
indr.setText(ipp);
}
public void AddData() {
save.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
myDB.insertData(ip_txt.getText().toString(),
term_txt.getText().toString());
MainActivity.indr.setText(ip_txt.getText().toString());
MainActivity.terminale.setText(term_txt.getText().toString());
Client.SERVER_IP = ip_txt.getText().toString();
finish();
}
}
);
}
}
( If I did not explain it i want to start the handler on the start of the app and also to start it again or immediatly after i change the data in EditText ip_txt or in EditText term_txt )
I would create Variables to store the handler and the runnable, then when you want to restart it just use:
yourHandler.removeCallback(yourRunnable);
yourHandler.postDelayed(yourRunnable,time);
and to start it, just do it as you did,
yourHandler.postDelayed(yourRunnable,5000);
Hope is what you are looking for.
How to create them:
public class ClassName{
Handler yourHandler = new Handler();
Runnable yourRunnable = new Runnable(){
#Override
public void run() {
//yourCode
}
};
// Rest of class code
}
Is just same as you did in your code but in a variable.

Button setText() wouldn't actually setText

I am trying to setText() to
Button btnFloor, btnTable;
Which isn't working ATM, actually I'm trying to send data from
FloorsActivity -> TablesActivity -> NewOrdersActivity
So how I pass Data from a activity to another?
FloorsActivity.java
#Override
public void onFloorItemClicked(int id) {
Intent intent = new Intent(this, TablesActivity.class);
intent.putExtra("FloorId", id);
startActivity(intent);
Toast.makeText(this, "Floor id : " + String.valueOf(id), Toast.LENGTH_SHORT).show();
}
TablesActivity.java
int floorId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_floors_tables);
initViews();
Intent intent = getIntent();
floorId = intent.getIntExtra("FloorId", 1);
}
#Override
public void onTableItemClicked(String name) {
String floorName = "F" + floorId;
Intent intent = new Intent(this, NewOrderActivity.class);
intent.putExtra("FloorId", floorId);
intent.putExtra("TableName", name);
intent.putExtra("FloorName", floorName);
startActivity(intent);
Toast.makeText(this, "Table Name : " + String.valueOf(name), Toast.LENGTH_SHORT).show();
}
NewOrderActivity.java
String floorName;
String tableName;
int floorId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_order);
initViews();
Intent intent = getIntent();
floorName = intent.getStringExtra("FloorName");
tableName = intent.getStringExtra("TableName");
floorId = intent.getIntExtra("FloorId", 1);
}
public void initViews() {
// Fetch view
btnFloor = (Button) findViewById(R.id.btn_floor);
btnTable = (Button) findViewById(R.id.btn_table);
//Set Views
btnFloor.setText(floorName);
btnTable.setText(tableName);
btnFloor.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(NewOrderActivity.this, FloorsActivity.class);
startActivity(intent);
}
});
btnTable.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(NewOrderActivity.this, TablesActivity.class);
intent.putExtra("FloorId", floorId);
startActivity(intent);
}
});
NewOrdersActivity is where I'm trying to set text
Here is my commit on Github for this full change
Here is the link to this project
You call initViews() before you've overloaded the intent extra's.
Fixed NewOrderActivity.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_order);
Intent intent = getIntent();
floorName = intent.getStringExtra("FloorName");
tableName = intent.getStringExtra("TableName");
floorId = intent.getIntExtra("FloorId", 1);
initViews();
}

Activity called outside the tab

I am developing an app with 5 tabs and my last tab displays a list of menus. The problem appears when I click a menu tab, the menu activity appears nicely below my tab but when I click any of the menus (which it will call LoginActivity), the new Activity appears full screen not under the tab. How can I handle this? Below is my code.
TabActivity
package com.smartag.smarttreasure;
public class NfcSurveyActivity extends TabActivity {
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
mAdapter.enableForegroundDispatch(this, mPendingIntent, mFilters,
mTechLists);
int profileCount = db.getContactsCount();
if (profileCount <= 0) {
Intent intent = new Intent(getApplicationContext(),
LoginActivity.class);
startActivity(intent);
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
int profileCount = db.getContactsCount();
if (profileCount <= 0) {
Intent intent1 = new Intent(getApplicationContext(),
LoginActivity.class);
startActivity(intent1);
}
Bundle extras = getIntent().getExtras();
if (extras != null) {
tabToDisplay = extras.getString("tab");
if (tabToDisplay.equals("CAMERA")) {
barcodeData = extras.getString("barcodeData");
}
extras.clear();
}
TabHost tabHost = getTabHost();
// Home
TabSpec tbspecHome = tabHost.newTabSpec("Home");
tbspecHome.setIndicator("",
getResources().getDrawable(R.drawable.tab_account_style));
Intent iHome = new Intent(this, HomeActivity.class);
tbspecHome.setContent(iHome);
tabHost.addTab(tbspecHome);
// History
tabHost.addTab(tabHost
.newTabSpec("Fun")
.setIndicator("",
getResources().getDrawable(R.drawable.tab_fun_style))
.setContent(
new Intent(this, NfcSurveyActivity.class)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)));
if (tabToDisplay != null && tabToDisplay.equals("REDEEM")) {
if (barcodeData != null && barcodeData.length() > 0) {
tabHost.addTab(tabHost
.newTabSpec("Camera")
.setIndicator(
"",
getResources().getDrawable(
R.drawable.tab_redeem_style))
.setContent(
new Intent(this, NfcSurveyActivity.class)
.addFlags(
Intent.FLAG_ACTIVITY_CLEAR_TOP)
.putExtra("autoLoadBarcodeData",
barcodeData)));
}
else {
tabHost.addTab(tabHost
.newTabSpec("Camera")
.setIndicator(
"",
getResources().getDrawable(
R.drawable.tab_redeem_style))
.setContent(
new Intent(this, NfcSurveyActivity.class)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)));
}
} else {
tabHost.addTab(tabHost
.newTabSpec("Camera")
.setIndicator(
"",
getResources().getDrawable(
R.drawable.tab_redeem_style))
.setContent(
new Intent(this, NfcSurveyActivity.class)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)));
}
// tabHost.setCurrentTab(2);
tabHost.getTabWidget().getChildAt(2).getLayoutParams().height = tabHost
.getTabWidget().getChildAt(2).getLayoutParams().height + 19;
// Search
TabSpec tbspecSearch = tabHost.newTabSpec("Finder");
tbspecSearch.setIndicator("",
getResources().getDrawable(R.drawable.tab_finder_style));
Intent iSearch = new Intent(this, NfcSurveyActivity.class);
tbspecSearch.setContent(iSearch);
tabHost.addTab(tbspecSearch);
// Profile
TabSpec tbspecProfile = tabHost.newTabSpec("Quit");
tbspecProfile.setIndicator("",
getResources().getDrawable(R.drawable.tab_quit_style));
Intent iProfile = new Intent(this, NfcSurveyActivity.class);
tbspecProfile.setContent(iProfile);
tabHost.addTab(tbspecProfile);
for (int i = 0; i <= 4; i++) {
tabHost.getTabWidget()
.getChildTabViewAt(i)
.setBackgroundColor(
getResources()
.getColor(android.R.color.transparent));
if (i == 2) {
tabHost.getTabWidget()
.getChildTabViewAt(i)
.setPadding(
tabHost.getTabWidget().getChildTabViewAt(i)
.getPaddingLeft(),
tabHost.getTabWidget().getChildTabViewAt(i)
.getPaddingTop(),
tabHost.getTabWidget().getChildTabViewAt(i)
.getPaddingRight(), 20);
}
}
if (tabToDisplay != null && tabToDisplay.length() > 0) {
if (tabToDisplay.equals("CAMERA")) {
tabHost.setCurrentTab(2);
} else if (tabToDisplay.equals("HISTORY")) {
tabHost.setCurrentTab(1);
}
}
tabHost.setOnTabChangedListener(new OnTabChangeListener() {
public void onTabChanged(String tabId) {
NfcSurveyConfiguration.SelectedTab = tabId;
}
});
}
}
MenuActivity
public class HomeActivity extends ListActivity {
static final String[] Account = new String[] { "Point History", "Scan History",
"Reward/Coupon History", "Share/Transfer History", "Personalise" };
String tabToDisplay = "";
String barcodeData = "";
SharedPreferences nfcSurveyConfiguration;
String profileId;
String pleaseWait = "";
protected boolean _taken;
protected File _directory;
protected String _filename;
protected String _fileExtension;
String profileName = "";
String profileEmail = "";
String profileStatus = "";
String profileLanguage = "";
String profileType = "";
DatabaseHandler db = new DatabaseHandler(this);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this,
R.layout.listview_item_row, Account));
ListView listView = getListView();
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
//Toast.makeText(getApplicationContext(),
// ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
Intent intent1 = new Intent(getApplicationContext(),
LoginActivity.class);
startActivity(intent1); // This activity appears not in the tab
}
});
}
#Override
public void onPause() {
super.onPause();
NfcSurveyConfiguration.CurrentActiveTab = 0;
}
}
Any suggestion or advice is highly appreciated.
this code inside setOnItemClickListener help me to solve the problem.
View view1 = getLocalActivityManager().startActivity(
"ReferenceName",
new Intent(getApplicationContext(),
YourActivityClass.class)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
.getDecorView();
setContentView(view1);

Categories

Resources