Activity called outside the tab - java

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);

Related

Getting data in intent giving error in only one activity

I'm trying to pass an intent from adapter and get it in my activity.
Whenever I did this it went to the else condition.
It doesn't get the value and I don't no why. When I try the same code in any other activity it worked perfectly, but in this activity it always gives a null value in intent.
I know there are so many answers to how to get and pass intent, but in my case it doesn't work in one activity and I don't know why.
My Adapter class:
holder.getSurvey.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context,AuthorMainScreen.class);
intent.putExtra("work", "getting");
context.startActivity(intent);
}
My AuthorMainScreen Activity:
public class AuthorMainScreen extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
Button newSurveyBtn, surveyWithRef, surveyResult;
ArrayList<JSONObject> jsonObjects = new ArrayList<JSONObject>();
public static TextView textView;
DatabaseReference databaseReference, surveyReference;
String referenceNo, loggedInUserId;
AlertDialog dialog;
ProgressDialog progressDialog;
DrawerLayout drawerLayout;
NavigationView navigationView;
LinearLayout linearLayout;
FirebaseAuth firebaseAuth;
TextView headerEmailView, rateOk;
Button headerLogout;
EditText reference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_author_navigation);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Processing your request...");
viewDeclaration();
clickFunctionalities();
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawerLayout, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawerLayout.setDrawerListener(toggle);
toggle.syncState();
//drawerLayout.addDrawerListener(actionBarDrawerToggle);
navigationView.setNavigationItemSelectedListener(this);
}
private void clickFunctionalities() {
newSurveyBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
surveyTitleDialog();
}
});
surveyWithRef.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
referenceDialog();
rateOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
referenceNo = reference.getText().toString().trim();
if (!referenceNo.isEmpty()) {
progressDialog.show();
getSurvey();
dialog.dismiss();
} else {
progressDialog.dismiss();
reference.setError("Reference # is required");
}
}
});
}
});
surveyResult.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
referenceDialog();
rateOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
referenceNo = reference.getText().toString().trim();
if (!referenceNo.isEmpty()) {
progressDialog.show();
getSurveyResultFile();
dialog.dismiss();
} else {
progressDialog.dismiss();
reference.setError("Reference # is required");
}
}
});
}
});
linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
} else {
drawerLayout.openDrawer(GravityCompat.START);
}
}
});
headerLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirebaseAuth.getInstance().signOut();
Intent intent = new Intent(AuthorMainScreen.this, LoginSignupActivity.class);
startActivity(intent);
finish();
}
});
}
private void surveyTitleDialog() {
final AlertDialog.Builder textBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
View view = inflater.inflate(R.layout.survey_name_dialog, null);
final EditText surveyName = view.findViewById(R.id.edt_set_survey_name);
TextView ok = view.findViewById(R.id.survey_name_btn);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String surveyTitleName = surveyName.getText().toString().trim();
if (!surveyTitleName.equals("")) {
dialog.dismiss();
Intent intent = new Intent(AuthorMainScreen.this, MakeSurvey.class);
intent.putExtra("surveyname", surveyTitleName);
Toast.makeText(AuthorMainScreen.this, surveyTitleName, Toast.LENGTH_SHORT).show();
startActivity(intent);
} else {
surveyName.setError("Title is Required");
}
}
});
TextView cancelBtn = view.findViewById(R.id.dismiss_dialog);
cancelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
textBuilder.setView(view);
dialog = textBuilder.create();
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
dialog.show();
Window window = dialog.getWindow();
window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
dialog.setCancelable(false);
}
private void getSurvey() {
surveyReference = FirebaseDatabase.getInstance().getReference().child(Constants.content).child(Constants.survey).child(referenceNo);
surveyReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
System.out.println(dataSnapshot);
if (dataSnapshot.hasChildren()) {
progressDialog.dismiss();
Intent intent = new Intent(getApplicationContext(), GetSurveys.class);
intent.putExtra(Constants.ref_no, referenceNo);
startActivity(intent);
} else {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), "Reference number is not valid !!!", Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), "Something went wrong!!!", Toast.LENGTH_SHORT).show();
}
});
}
public void getSurveyResultFile() {
databaseReference = FirebaseDatabase.getInstance().getReference().child(Constants.content).child(Constants.Answers).child(loggedInUserId).child(referenceNo);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
progressDialog.dismiss();
JSONArray dataSnapshotArray = new JSONArray();
JSONArray dataSnapshotChildrenArray;
JSONObject dataSnapshotChildrenAnswer;
JSONArray dataSnapshotChildrenAnswerValues;
for (DataSnapshot ds : dataSnapshot.getChildren()) {
System.out.println("sdsd" + ds);
dataSnapshotChildrenArray = new JSONArray();
ArrayList<Object> list = (ArrayList<Object>) ds.getValue();
for (int i = 0; i < list.size(); i++) {
HashMap<String, Object> map = (HashMap<String, Object>) list.get(i);
Iterator<Map.Entry<String, Object>> finalIterator = map.entrySet().iterator();
dataSnapshotChildrenAnswer = new JSONObject();
while (finalIterator.hasNext()) {
Map.Entry<String, Object> entry = finalIterator.next();
Object value = entry.getValue();
String key = entry.getKey();
try {
dataSnapshotChildrenAnswer.put(key, value);
if (value instanceof ArrayList) {
dataSnapshotChildrenAnswerValues = new JSONArray();
ArrayList<String> answers = (ArrayList<String>) value;
for (int j = 0; j < answers.size(); j++) {
dataSnapshotChildrenAnswerValues.put(answers.get(j));
}
dataSnapshotChildrenAnswer.put(key, dataSnapshotChildrenAnswerValues);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
dataSnapshotChildrenArray.put(dataSnapshotChildrenAnswer);
}
dataSnapshotArray.put(dataSnapshotChildrenArray);
System.out.println("jso " + dataSnapshotArray);
}
try {
saveCsv(dataSnapshotArray);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(AuthorMainScreen.this, "Sorry!!user or survey not found.", Toast.LENGTH_LONG).show();
progressDialog.dismiss();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
public void saveCsv(JSONArray outerArray) throws IOException, JSONException {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}
}
String fileName = referenceNo + " Result";
String rootPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/test/";
File dir = new File(rootPath);
if (!dir.exists()) {
dir.mkdir();
}
File file = null;
file = new File(rootPath, fileName);
if (!file.exists()) {
progressDialog.dismiss();
file.createNewFile();
}
if (file.exists()) {
progressDialog.dismiss();
CSVWriter writer = new CSVWriter(new FileWriter(file), ',');
for (int i = 0; i < outerArray.length(); i++) {
JSONArray innerJsonArray = (JSONArray) outerArray.getJSONArray(i);
for (int k = 0; k < innerJsonArray.length(); k++) {
String[][] arrayOfArrays = new String[innerJsonArray.length()][];
JSONObject innerJsonObject = (JSONObject) innerJsonArray.getJSONObject(k);
String[] stringArray1 = new String[innerJsonObject.length()];
//stringArray1[0]= (String) innerJsonObject.getString("type");
stringArray1[1] = "Questions";
stringArray1[2] = "Answers";
stringArray1[1] = (String) innerJsonObject.getString("title");
stringArray1[2] = "";
JSONArray jsonArray = (JSONArray) innerJsonObject.getJSONArray("answer");
for (int j = 0; j < jsonArray.length(); j++) {
stringArray1[2] += jsonArray.get(j).toString();
stringArray1[2] += ",";
}
arrayOfArrays[k] = stringArray1;
writer.writeNext(arrayOfArrays[k]);
System.out.println("aa " + Arrays.toString(arrayOfArrays[k]));
}
}
writer.close();
Toast.makeText(this, fileName + " is been saved at " + rootPath, Toast.LENGTH_LONG).show();
}
}
public void referenceDialog() {
final AlertDialog.Builder rateBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
View view = inflater.inflate(R.layout.survey_refno_dialog, null);
reference = view.findViewById(R.id.edt_survey_ref_no);
rateOk = view.findViewById(R.id.ref_btnOk);
TextView rateCancel = view.findViewById(R.id.ref_btnCancel);
rateBuilder.setView(view);
rateCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
dialog = rateBuilder.create();
dialog.show();
Window rateWindow = dialog.getWindow();
rateWindow.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
dialog.setCancelable(false);
}
private void viewDeclaration() {
newSurveyBtn = findViewById(R.id.new_surveys_button);
surveyWithRef = findViewById(R.id.get_survey_button);
surveyResult = findViewById(R.id.analyze_survey);
linearLayout = findViewById(R.id.hamburg_icon_layout);
drawerLayout = findViewById(R.id.drawer_layout);
navigationView = findViewById(R.id.navigation_view);
View view = navigationView.getHeaderView(0);
headerEmailView = view.findViewById(R.id.header_email);
headerLogout = findViewById(R.id.nav_logout);
firebaseAuth = FirebaseAuth.getInstance();
if (firebaseAuth.getCurrentUser() != null) {
String userEmail = firebaseAuth.getCurrentUser().getEmail();
headerEmailView.setText(userEmail);
}
if (firebaseAuth.getCurrentUser() != null && firebaseAuth.getCurrentUser().getUid() != null) {
loggedInUserId = firebaseAuth.getCurrentUser().getUid();
}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.menu_share:
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, "DataPro");
intent.putExtra(Intent.EXTRA_TEXT, Constants.shareMessage);
startActivity(Intent.createChooser(intent, "Share Via"));
drawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.menu_survey_count:
startActivity(new Intent(getApplicationContext(), UserAllSurveys.class));
drawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.menu_new_instruments:
startActivity(new Intent(getApplicationContext(), CreateInstrument.class));
drawerLayout.closeDrawer(GravityCompat.START);
break;
case R.id.menu_about_us:
Toast.makeText(getApplicationContext(), "About us", Toast.LENGTH_SHORT).show();
drawerLayout.closeDrawer(GravityCompat.START);
break;
}
return true;
}
#Override
protected void onStart() {
super.onStart();
Intent intent = getIntent();
/* if (intent.hasExtra("work") ) {
String k = getIntent().getStringExtra("work");
Toast.makeText(this, k, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "eroor", Toast.LENGTH_SHORT).show();
} */
Bundle bundle = getIntent().getExtras();
if (bundle != null ) {
String k = bundle.getString("work");
Toast.makeText(this, k, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "error", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
Try like this
Bundle bundle = getIntent().getExtras();
if (bundle != null ) {
String k = bundle.getString("work");
Toast.makeText(this, k, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "error" , Toast.LENGTH_SHORT).show();
}
Do you have another class with the same class name, but different package name?
Because it seems like there is no extra parameter present in your receiver activity (AuthorMainScreen). Sometimes mistakes like this can take more time than any other logical mistake. Or you can try to call it onCreate() by commenting the rest of the code. Just check this.

How to avoid an activity to reload every time i get into it?

Hello I have an activity which shows some listviews, and I want them not to reload/refresh every time I get into it, as it is programmed to show different items every time.
But I want it not to refresh until a button which is in another activity is pushed.
I've not tried anything yet as I don't know what to start with.
Here I leave you the code of the java.class:
public class Comida extends AppCompatActivity implements Adaptador2.OnRecipeListener {
private RecyclerView recyclerView1;
List<Entidad2> listItems;
Adaptador2 adaptor;
private Entidad2 entidad1,entidad2,entidad3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
String myValue = savedInstanceState.getString("key");
}
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_comida);
recyclerView1 = findViewById(R.id.lv_1);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView1.setLayoutManager(layoutManager);
listItems = new ArrayList<>();
entidad1 = new Entidad2(R.drawable.calabacines_3, "Solomillo a la plancha", " 10 min.", 4, 20);
entidad2 = new Entidad2(R.drawable.patatas_deluxe_especiadas_70523_300_150, "Entrecot", " 15 min.", 2, 50);
entidad3 = new Entidad2(R.drawable.tomate, "Hamburguesa", " 2 min.", 5, 100);
listItems.add(entidad1);
listItems.add(entidad2);
listItems.add(entidad3);
adaptor = new Adaptador2(listItems, this);
recyclerView1.setAdapter(adaptor);
adaptor.notifyDataSetChanged();
pickEntidad();
}
#Override
public void OnRecipe(int priority) {
if (priority == 20) {
Intent in = new Intent(this, Solomillo.class);
startActivity(in);
}
if (priority == 50) {
Intent in = new Intent(this, Entrecot.class);
startActivity(in);
}
if (priority == 100) {
Intent in = new Intent(this, Hamburguesa.class);
startActivity(in);
}
}
private void pickEntidad(){
final int random = new Random().nextInt(101);
int priority1 = entidad1.getPriority();
int priority2 = entidad2.getPriority();
int priority3 = entidad3.getPriority();
listItems.clear();
if(random < priority1){
listItems.add(entidad1);
}else if(random < priority2){
listItems.add(entidad2);
}else if (random <= priority3){
listItems.add(entidad3);
}
adaptor.notifyDataSetChanged();
}
}
And then here there is the java.class of the other activity(the one which contains the button that has to refresh the other activity):
The button which I want to use to refresh the activity is the boton_prueba.
public class Menu extends AppCompatActivity {
Button boton_start;
Button boton_refresh;
Button boton_prueba;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
boton_start=(Button) findViewById(R.id.boton_platos);
boton_refresh = (Button) findViewById(R.id.boton_cambiarmenu);
boton_prueba=(Button) findViewById(R.id.boton_menu);
boton_start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent in = new Intent(Menu.this,Dishes.class);
startActivity(in);
}
});
boton_prueba.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent in = new Intent(Menu.this,Comida.class);
startActivity(in);
}
});
boton_refresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//What to do?
}
});
}
}
Please if anyone has any idea of how to do it help me and in case you need more code or information just tell me.
Thank you.
If I really understand you then you want to execute pickEntidad() method when pressing in refresh button and go to this activity so you can do that using send any number or data with the intent like:
Intent in = new Intent(currentActivity.this,targetActivity.class);
in.putExtra("number",2);
startActivity(in);
and in target activity use somthing like this:
if(getIntent().getIntExtra("number",-1) ==2)
{
// what do you want to do...
}

How to use a variable in a new activity?

I added a variable that pass form the first activity to the second one.
I want to use the info that has accepted from the first activity, at the new activity, and will save it on new double variable, display it as permanent on a textView.
Now, it appears only when I am clicking on the regular button that start the new activity.
As first step, I guess, I need to remove - "startActivity(intent1);".
How should I move on from here?
Java code:
First Activity (Name : settings.java)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
}
public void onClick (View v){
Intent intent = new Intent(settings.this, WaitressRecord.class);
startActivity(intent);
}
protected void onClickWait (View v) {
//--- Casting & Converting EditText "etSalaryWaitress" to Double "doubleSW".
btnWaitress =(Button)findViewById(R.id.btnWaitress);
etSalaryWaitress = (EditText) findViewById(R.id.etSalaryWaitress);
doubleSW = Double.parseDouble(etSalaryWaitress.getText().toString());
//---Casting Radio Button(s).
rbPercentage = (RadioButton)findViewById(R.id.rbPercentage);
rbShekel = (RadioButton)findViewById(R.id.rbShekel);
if (doubleSW < 100 ) {
if (rbPercentage.isChecked()) {
HafrashaP = 1 - (doubleSW / 100.0);
strHafPer = String.valueOf(HafrashaP);
Toast.makeText(settings.this, strHafPer, Toast.LENGTH_SHORT).show();
// start the SecondActivity
Intent intent1 = new Intent(this, WaitressRecord.class);
intent1.putExtra(Intent.EXTRA_TEXT, strHafPer);
startActivity(intent1);
} else if (rbShekel.isChecked()) {
HafrashaS = -doubleSW;
strHafShek = String.valueOf(HafrashaS);
Toast.makeText(settings.this, strHafShek, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(settings.this, "לא הוזנה סוג ההפרשה", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(settings.this, "מספר שגוי", Toast.LENGTH_SHORT).show();
}
}
New Activity: (Name : WaitressRecord.java)
public class WaitressRecord extends AppCompatActivity {
String strHafPer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_waitress_record);
// get the text from MainActivity
Intent intent1 = getIntent();
strHafPer = intent1.getStringExtra(Intent.EXTRA_TEXT);
// use the text in a TextView
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(strHafPer);
}
}
//First Activity
Intent intent= new Intent(this, SecondActivity.class);
Bundle extra = new Bundle();
mBundle.putString(VARIABLE_KEY, value);
intent.putExtras(mBundle);
startActivity(intent);
//on the second Acitivty
intent intent = getIntent();
Bundle bundleExtra;
//Null Checking
if (intent != null ) {
bundleExtra = getIntent().getExtras();
// Be sure your check your "VARIABLE KEY SAME AS in THE FIRST ACTIVITY
String resultString = extras.getString("VARIABLE_KEY");
}

One of my Android activities work badly

Hello dear StackOverflow community!!!
While developing my recent application project i found some problems while debugging the app. In my project i want to pass one data element through 2 activities. Everything looks good (no errors or other stuff) until i choose WatchingActivity in my app. It displays no webview but only white blank space while there should be video choosen in PartActivity. Please help!!!!
public class MainActivity extends AppCompatActivity {
String clipname;
ImageView ka;
ImageView jb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ka = (ImageView) findViewById(R.id.imageView1);
jb = (ImageView) findViewById(R.id.imageView2);
}
public void imageView1Clicked(View view) {
// method that is signed in layout file to be called by clicking on imageView1
clipname="Kendra's Adventure";
Intent mainintent = new Intent(this, ChooseAPartActivity.class);
mainintent.putExtra("CLIP", clipname);
startActivity(mainintent);
}
public void imageView2Clicked(View view) {
clipname="Johhny Big";
Intent mainintent = new Intent(this, ChooseAPartActivity.class);
mainintent.putExtra("CLIP", clipname);
startActivity(mainintent);
}
}
public class ChooseAPartActivity extends AppCompatActivity {
TextView title;
TextView part1;
TextView part2;
TextView part3;
TextView part4;
TextView part5;
TextView part6;
String videoname;
String partnumber;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choose_a_part);
title.findViewById(R.id.textView);
title.findViewById(R.id.textView);
Intent mainintent = getIntent();
String clipname = mainintent.getStringExtra("CLIP");
title.setText(clipname);
videoname = clipname;
}
public void partone (View view) {
//method assigned to textview in layout file
partnumber = "one";
Intent partintent = new Intent(this, WatchingActivity.class);
partintent.putExtra("PART", videoname);
partintent.putExtra("NUMBER", partnumber);
startActivity(partintent);
}
public void parttwo (View view) {
partnumber = "two";
Intent partintent = new Intent(this, WatchingActivity.class);
partintent.putExtra("PART", videoname);
partintent.putExtra("NUMBER", partnumber);
startActivity(partintent);
}
public void partthree (View view) {
partnumber = "three";
Intent partintent = new Intent(this, WatchingActivity.class);
partintent.putExtra("PART", videoname);
partintent.putExtra("NUMBER", partnumber);
startActivity(partintent);
}
public void partfour (View view) {
partnumber = "four";
Intent partintent = new Intent(this, WatchingActivity.class);
partintent.putExtra("PART", videoname);
partintent.putExtra("NUMBER", partnumber);
startActivity(partintent);
}
public void partfive (View view) {
partnumber = "five";
Intent partintent = new Intent(this, WatchingActivity.class);
partintent.putExtra("PART", videoname);
partintent.putExtra("NUMBER", partnumber);
startActivity(partintent);
}
public void partsix (View view) {
partnumber = "six";
Intent partintent = new Intent(this, WatchingActivity.class);
partintent.putExtra("PART", videoname);
partintent.putExtra("NUMBER", partnumber);
startActivity(partintent);
}
}
public class WatchingActivity extends AppCompatActivity {
String clipkey;
WebView screen;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_watching);
Intent sceneintent = getIntent();
String videoname = partintent.getStringExtra("PART");
String partnumber = sceneintent.getStringExtra("NUMBER");
if(videoname == "Kendra's Adventure"){
if(partnumber == "one"){
clipkey = "<iframe width=\"95%\" height=\"95%\" src=\"links work fine i tried it many times so its not that\" frameborder=\"0\" allowfullscreen></iframe>";
}
}
else if(videoname == "Johnny Big"){
if(partnumber == "one") {
clipkey = "<iframe width=\"95%\" height=\"95%\" src=\"\" frameborder=\"0\" allowfullscreen></iframe>";
}
else if(partnumber == "two"){
clipkey = "<iframe width=\"95%\" height=\"95%\" src=\"\" frameborder=\"0\" allowfullscreen></iframe>";
}
}
screen=(WebView)findViewById(R.id.webView);
screen.getSettings().setJavaScriptEnabled(true);
String myvideokey = clipkey;
screen.loadData(myvideokey, "text/html", "utf-8");
screen.setWebChromeClient(new WebChromeClient(){
});
}
}
String videoname = partintent.getStringExtra("PART");
Is that line ok in WatchingActivity? There is no partintent field or something.
Defining all activities in the same class-file is not really good idea.

Android activity is returning null through intent

Not sure why I keep getting a null reference when I am trying to return data to Main activity from another activity (done through Intents). I've tried to Serialize everything, and tried other stuff. I don't know what may be causing it. Can some one point out my mistake?
Here is the error I keep getting:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=10, result=0, data=null} to activity {ebadly.com.youstreamer/ebadly.com.youstreamer.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.Serializable android.content.Intent.getSerializableExtra(java.lang.String)' on a null object reference
Here is the code in my MainActivity class:
public static final int PICK_CONTACTS = 10;
public ArrayList<Contact> mSendPhoneNumbers;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSendPhoneNumbers = new ArrayList<Contact>();
Button contactsButton = (Button)findViewById(R.id.select_contacts_button);
contactsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, ContactsListActivity.class);
i.putExtra(ContactsListActivity.EXTRA, mSendPhoneNumbers);
startActivityForResult(i, PICK_CONTACTS);
}
});
Button enterButton = (Button)findViewById(R.id.enter_button);
enterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
enter code here
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mSendPhoneNumbers = (ArrayList<Contact>)data.getSerializableExtra(ContactsListActivity.EXTRA);
}
Here is code from my ContactsListActivity class:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts_list);
mSendPhoneNumbers = new ArrayList<Contact>();
mSendPhoneNumbers = (ArrayList<Contact>) getIntent().getSerializableExtra(EXTRA);
mContacts = new ArrayList<Contact>();
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
while (phones.moveToNext())
{
Contact c = new Contact();
c.mName = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
c.mNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
mContacts.add(c);
}
phones.close();
if(!mSendPhoneNumbers.isEmpty() || mSendPhoneNumbers != null){
for(Contact c : mSendPhoneNumbers){
if(c.mChecked == true){
for(Contact search: mContacts){
if(search.mNumber.equals(c.mNumber)){
search.mChecked = true;
}
}
}
}
}
mContactsList = (ListView) findViewById(R.id.contact_list);
mContactsList.setAdapter(new ContactListViewAdapter(mContacts));
mContactsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Contact c = (Contact) parent.getAdapter().getItem(position);
if(c.mChecked == true) c.mChecked = false;
else c.mChecked = true;
}
});
}
#Override
public void onBackPressed(){
super.onBackPressed();
for(Contact addContact: mContacts){
if (addContact.mChecked){
for(Contact search : mSendPhoneNumbers){
if(search.mNumber.equals(addContact.mNumber)){
break;
}else mSendPhoneNumbers.add(addContact);
}
}
}
Intent i = new Intent();
Log.d("HEREEE === ", mSendPhoneNumbers.toString());
i.putExtra(EXTRA, mSendPhoneNumbers);
setResult(RESULT_OK, i);
finish();
}

Categories

Resources