I'm trying to replace a part of the text after clicking the bottom but I can't make it work. When I click the bottom without entering a name the message should say "Hello Username", and if I enter a name the "Username" should be replace by the name. Here is the code so far. Thanks
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
public class HelloAndroid extends AppCompatActivity implements OnClickListener {
private EditText name;
private TextView display;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hello_android);
name = (EditText) findViewById(R.id.name);
display = (TextView) findViewById(R.id.display);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_hello_android, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View view) {
if (button == view) {
String message = "Hello, Username " + name.getText().toString() + "!";
if (button == view) {
String username = "Hello " + name.getText().toString() + "";
Toast toast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
toast.show();
display.setText(message);
}
}
}
}
You are enable to do this because may be you are not getting click here . Here is my code change it .
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class HelloAndroid extends AppCompatActivity implements View.OnClickListener {
private EditText name;
private TextView display;
private Button button;
String message ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dummy);
name = (EditText) findViewById(R.id.name);
display = (TextView) findViewById(R.id.display);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.button :
if (name.getText().toString().isEmpty())
{
message = "Hello username" ;
}
else {
message = "Hello "+name.getText().toString() ;
}
Toast toast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
toast.show();
display.setText(message);
break;
}
}
}
Related
I'm developing a Grade/GPA Calculator app on Android during my free time. What the app basically does until now is let the user add Semesters in the Main Activity and when the user clicks on a certain Semester the user is redirected to another Activity where the user can add new Courses for that specific semester. The problem I'm having is that when the user hits on the back button to go to to the Main Activity where the Semesters are located the courses that were added in that semester are erased. The same happens when I go to the phone's homepage and re-launch the app, everything that the user had created has been deleted.
I'm pretty sure my problem is that I'm not saving the data that the user creates to the phone's storage/app's storage, but I can't seem to figure out on how to do this. If anyone can point me in the right direction I would appreciate it. Thanks!
This is my MainActivity class's code: (My MainActivity is where Semesters are added)
package com.example.gradecalculator;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import java.util.ArrayList;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
// Private Fields
private Dialog d;
private EditText semesterName;
private ListView semesterListView;
private ArrayList<String> semesterArray = new ArrayList<String>();
private SemesterAdapter customSemesterAdapter;
private ArrayList<Semester> mySemesters = new ArrayList<>();
private ArrayList<String> semesterBackgrounds = new ArrayList<String>();
private String getSemesterName;
private int randomBackground[] = new int[7];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initiating toolbar
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Making a new dialog
d = new Dialog(this);
// Initializing variables
semesterName = (EditText) d.findViewById(R.id.editTextSemesterName);
semesterListView = (ListView) findViewById(R.id.semesterList);
// Calling the removeSemesters() method
removeSemesters();
// Adding backgrounds to the backgrounds ArrayList
semesterBackgrounds.add("orange_background");
semesterBackgrounds.add("green_background");
semesterBackgrounds.add("aqua_background");
semesterBackgrounds.add("blue_background");
semesterBackgrounds.add("pink_background");
semesterBackgrounds.add("purple_background");
semesterBackgrounds.add("red_background");
semesterBackgrounds.add("yellow_background");
}
// Creating a custom Menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.top_menu, menu);
return true;
}
// Buttons in the custom Menu
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.editButton:
Toast.makeText(this, "Delete the desired Semesters by clicking on the trash button located to the right of each Semester", Toast.LENGTH_LONG).show();
return true;
}
return super.onOptionsItemSelected(item);
}
// When user clicks on "+New Semester" button open a popup where the user is prompted to
// type in the Semester Name and when "Done" is clicked the new semester appears in the Main
// Activity
public void newSemesterPopup(View v) {
TextView closePopup;
ImageButton doneButton;
d.setContentView(R.layout.new_semester_popup);
semesterName = (EditText) d.findViewById(R.id.editTextSemesterName);
semesterListView = (ListView) findViewById(R.id.semesterList);
doneButton = (ImageButton) d.findViewById(R.id.doneButton);
doneButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addSemesters();
}
});
closePopup = (TextView) d.findViewById(R.id.exitButton);
closePopup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
d.dismiss();
}
});
d.show();
}
// Adds semesters to Main Activity
public void addSemesters() {
getSemesterName = semesterName.getText().toString();
if (semesterArray.contains(getSemesterName)) {
Toast.makeText(getBaseContext(), "Semester Name Already Exists", Toast.LENGTH_SHORT).show();
} else if (getSemesterName == null || getSemesterName.trim().equals("")) {
Toast.makeText(getBaseContext(), "Cannot Add Empty Semester Name", Toast.LENGTH_SHORT).show();
} else {
semesterArray.add(getSemesterName);
mySemesters.add(new Semester(getSemesterName, semesterBackgrounds.get(new Random().nextInt(randomBackground.length))));
customSemesterAdapter = new SemesterAdapter(getApplicationContext(), R.layout.semester_row, mySemesters);
semesterListView.setAdapter(customSemesterAdapter);
d.dismiss();
}
}
// Removes unwanted semesters from Main Activity
public void removeSemesters() {
semesterListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
AlertDialog.Builder deleteAlert = new AlertDialog.Builder(MainActivity.this);
deleteAlert.setTitle("Semester Deletion Process");
deleteAlert.setMessage("Are you sure you want to delete the selected Semesters?");
deleteAlert.setNegativeButton("No! Cancel", null);
deleteAlert.setPositiveButton("Yes! Delete", new AlertDialog.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
customSemesterAdapter.remove(customSemesterAdapter.getItem(position));
semesterArray.remove(position);
customSemesterAdapter.notifyDataSetChanged();
Toast.makeText(MainActivity.this, "Semester Deleted Successfully.", Toast.LENGTH_SHORT).show();
}
});
deleteAlert.show();
return false;
}
});
openSemestersActivity();
}
// Open the SemesterActivity and uses .putExtra to pass data to the SemesterActivity to tell it what semester to render
// data accordingly
public void openSemestersActivity() {
final Intent semester = new Intent(this, SemesterActivity.class);
semesterListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
semester.putExtra("semester", semesterName.getText().toString());
startActivity(semester);
}
});
}
}
This is my SemesterActivity code: (My SemestersActivity is where Courses are added)
package com.example.gradecalculator;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import java.util.ArrayList;
import java.util.Random;
public class SemesterActivity extends AppCompatActivity {
// Private Fields
private Dialog d;
private EditText courseName;
private EditText courseCode;
private EditText courseCredits;
private ListView courseListView;
private ArrayList<String> courseArray = new ArrayList<String>();
private CourseAdapter customCourseAdapter;
private ArrayList<Course> myCourses = new ArrayList<>();
private ArrayList<String> coursesBackgrounds = new ArrayList<String>();
private String getCourseName;
private String getCourseCode;
private String getCourseCredits;
private int randomBackground[] = new int[7];
private TextView courseNameView;
private TextView courseCodeView;
private TextView courseCreditsView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_semester);
d = new Dialog(this);
courseNameView = (TextView) d.findViewById(R.id.editTextCourseName);
courseCodeView = (TextView) d.findViewById(R.id.editTextCourseCode);
courseCreditsView = (TextView) d.findViewById(R.id.editTextCourseCredits);
courseListView = (ListView) findViewById(R.id.coursesList);
// Retrieving the Extra and determining the semester we want to load
Intent myIntent = getIntent();
String semester = myIntent.getStringExtra("semester");
removeCourses();
// Initiating toolbar
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Adding backgrounds to the backgrounds ArrayList
coursesBackgrounds.add("orange_background_big");
coursesBackgrounds.add("green_background_big");
coursesBackgrounds.add("aqua_background_big");
coursesBackgrounds.add("blue_background_big");
coursesBackgrounds.add("pink_background_big");
coursesBackgrounds.add("purple_background_big");
coursesBackgrounds.add("red_background_big");
coursesBackgrounds.add("yellow_background_big");
}
// Creating a custom Menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.top_menu, menu);
return true;
}
// Buttons in the custom Menu
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.editButton:
Toast.makeText(this, "Delete the desired Courses by clicking on the trash button located to the right of each Semester", Toast.LENGTH_LONG).show();
return true;
}
return super.onOptionsItemSelected(item);
}
// New course popup
public void newCoursePopup(View v) {
TextView closePopup;
ImageButton doneButton;
d.setContentView(R.layout.new_course_popup);
courseName = (EditText) d.findViewById(R.id.editTextCourseName);
courseCode = (EditText) d.findViewById(R.id.editTextCourseCode);
courseCredits = (EditText) d.findViewById(R.id.editTextCourseCredits);
doneButton = (ImageButton) d.findViewById(R.id.doneButton);
doneButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addCourses();
}
});
closePopup = (TextView) d.findViewById(R.id.exitButton);
closePopup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
d.dismiss();
}
});
d.show();
}
// Adding courses to the Semester
public void addCourses() {
getCourseName = courseName.getText().toString();
getCourseCode = courseCode.getText().toString();
getCourseCredits = courseCredits.getText().toString();
if(courseArray.contains(getCourseName)) {
Toast.makeText(getBaseContext(), "Course Name Already Exists", Toast.LENGTH_SHORT).show();
}
else if(getCourseName == null || getCourseName.trim().equals("")) {
Toast.makeText(getBaseContext(), "Cannot Add Empty Course Name", Toast.LENGTH_SHORT).show();
}
else {
courseArray.add(getCourseName);
myCourses.add(new Course(getCourseName, getCourseCode, getCourseCredits, coursesBackgrounds.get(new Random().nextInt(randomBackground.length))));
customCourseAdapter = new CourseAdapter(getApplicationContext(), R.layout.course_row, myCourses);
courseListView.setAdapter(customCourseAdapter);
d.dismiss();
}
}
// Removing courses from the Semester
public void removeCourses() {
courseListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
AlertDialog.Builder deleteAlert = new AlertDialog.Builder(SemesterActivity.this);
deleteAlert.setTitle("Course Deletion Process");
deleteAlert.setMessage("Are you sure you want to delete the selected Courses?");
deleteAlert.setNegativeButton("No! Cancel", null);
deleteAlert.setPositiveButton("Yes! Delete", new AlertDialog.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
customCourseAdapter.remove(customCourseAdapter.getItem(position));
courseArray.remove(position);
customCourseAdapter.notifyDataSetInvalidated();
Toast.makeText(SemesterActivity.this, "Course Deleted Successfully", Toast.LENGTH_SHORT).show();
}
});
deleteAlert.show();
return false;
}
});
}
}
There are a couple of databases you can look into; You can use Room or Realm. You can also check out online DBs like Firestore by Firebase. The beauty about having an online db a user(Student) can access their data from a different phone if they lose or replace their current one. A recommended way to go is to have both to cover both scenarios.
I can not figure out why this code output always show NaN. Is there anybody who can help me figure out where I did mistake?
package com.example.user.solar_calculator;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.content.Context;
import android.content.Intent;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.Toast;
public class efficiency extends Activity {
Button button;
EditText efficiency;
EditText vol;
String e,v;
double e1,wat,v1, AC_Load_in_ampere_hour_calculation,dc;
double load,load_vol,Total_Daily_load,lol;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_efficiency);
initControls();
addListenerOnButton();
}
public void initControls() {
efficiency=(EditText)findViewById(R.id.editText1);
vol=(EditText)findViewById(R.id.editText2);
button=(Button)findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
e1=Double.parseDouble(efficiency.getText().toString()); // Make use of autoboxing. It's also easier to read.
} catch (NumberFormatException e) {
e1=1;
}
try {
v1=Double.parseDouble(vol.getText().toString());// Make use of autoboxing. It's also easier to read.
} catch (NumberFormatException e) {
v1=1;
}
Bundle extras = getIntent().getExtras();
if(extras !=null) {
String value = extras.getString("FOUR");
load=Double.parseDouble(value.toString());
}
wat=load_vol*(1+.1);
AC_Load_in_ampere_hour_calculation = (load)/( v1* (e1/100));
Total_Daily_load=AC_Load_in_ampere_hour_calculation+dc;
Intent i = new Intent(efficiency.this, calculation.class);
//Create the bundle
Bundle bundle = new Bundle();
//Add your data to bundle
bundle.putString("seven", String.valueOf(AC_Load_in_ampere_hour_calculation));
bundle.putString("eight", String.valueOf(Total_Daily_load));
bundle.putString("nine", String.valueOf(dc));
//Add the bundle to the intent
i.putExtras(bundle);
//Fire that second activity
startActivity(i);
}
});
}
public void addListenerOnButton() {
final Context context = this;
button = (Button) findViewById(R.id.button);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I think the line who cause problem is AC_Load_in_ampere_hour_calculation = (load)/( v1* (e1/100));
Because if v1 = 0 it will be impossible.
MainActivity mActivity = new MainActivity();
mActivity.countRecords();
The Way I Used to call function countRecords() Which it was inside OnClickListenerCreateStudent class But I found the message when the button is pressed but with this a way no problems
((MainActivity)context).countRecords(); What is the difference between them now ?
package com.example.train1;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonCreateLocation = (Button) findViewById(R.id.buttonCreateStudent);
buttonCreateLocation.setOnClickListener(new OnClickListenerCreateStudent());
countRecords();
}
public void countRecords() {
int recordCount = new TableControllerStudent(this).count();
TextView textViewRecordCount = (TextView) findViewById(R.id.textViewRecordCount);
textViewRecordCount.setText(recordCount + " records found.");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
package com.example.train1;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import android.app.Activity;
public class OnClickListenerCreateStudent implements View.OnClickListener {
//MainActivity M_activity;
//MainActivity mActivity// = new MainActivity();
#Override
public void onClick(View view) {
//M_activity = new MainActivity();
final Context context = view.getContext();
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View formElementsView = inflater.inflate(R.layout.student_input_form, null, false);
final EditText editTextStudentFirstname = (EditText) formElementsView.findViewById(R.id.editTextStudentFirstname);
final EditText editTextStudentEmail = (EditText) formElementsView.findViewById(R.id.editTextStudentEmail);
new AlertDialog.Builder(context).setView(formElementsView).setTitle("Create Student")
.setPositiveButton("Add",
new DialogInterface.OnClickListener() {
// countRecords();
public void onClick(DialogInterface dialog, int id) {
String studentFirstname = editTextStudentFirstname.getText().toString();
String studentEmail = editTextStudentEmail.getText().toString();
ObjectStudent objectStudent = new ObjectStudent();
objectStudent.firstname= studentFirstname;
objectStudent.email= studentEmail;
// call to table controller stud and put objectData
boolean createSuccessful = new TableControllerStudent(context).create(objectStudent);
if(createSuccessful){
Toast.makeText(context, "Student information was saved.", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context, "Unable to save student information.", Toast.LENGTH_SHORT).show();
}
((MainActivity)context).countRecords();
MainActivity mActivity = new MainActivity();
mActivity.countRecords();
//((MainActivity)).
dialog.cancel();
}
}).show();
// Toast.makeText(context," "+context , Toast.LENGTH_LONG).show();
}
public class ObjectStudent {
int id;
String firstname;
String email;
public ObjectStudent(){
}
}
// class End
}
Never create your activities with the constructor, they're bound to not be initialized correctly sooner or later.
Create the Activity via the Intent, as in the docs:
Intent intent = new Intent(this, DisplayMessageActivity.class);
I have two activities. When I clicked on first activity in list view, second activity opened .Second activity have one button number of item. when I clicked on second activity number of count goes to first activity. It is repeated process but number of count in first activity also gets increased.
My first activity..
package com.firstchoicefood.phpexpertgroup.firstchoicefoodin;
import android.app.ActionBar;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AbsListView;
import android.os.Bundle;
import android.util.Log;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.adapter.ListAdapterAddItems;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.bean.ListModel;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.json.JSONfunctions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URLEncoder;
import java.util.ArrayList;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class DetaisRESTActivity extends Activity {
String messagevaluename,totalamount,valueid,valueid1,valuename,pos;
public String countString=null;
public int count=0;
public String message=null;
public static String message1=null;
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ArrayList aa;
public TextView mTitleTextView;
public ImageButton imageButton;
ListAdapterAddItems adapter;
public TextView restaurantname = null;
public TextView ruppees = null;
String restaurantmenuname,rastaurantname;
ProgressDialog mProgressDialog;
ArrayList<ListModel> arraylist;
public static String RASTAURANTNAMEDETAILS = "RestaurantPizzaItemName";
public static String RASTAURANTRUPPEES = "RestaurantPizzaItemPrice";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.activity_detais_rest);
// getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,R.layout.titlebar);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#ff0000")));
LayoutInflater mInflater = LayoutInflater.from(this);
View mCustomView = mInflater.inflate(R.layout.titlebar, null);
mTitleTextView = (TextView) mCustomView.findViewById(R.id.textView123456789);
imageButton = (ImageButton) mCustomView
.findViewById(R.id.imageButton2);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), "Refresh Clicked!",
Toast.LENGTH_LONG).show();
Intent i=new Intent(DetaisRESTActivity.this,TotalPriceActivity.class);
startActivity(i);
}
});
actionBar.setCustomView(mCustomView);
actionBar.setDisplayShowCustomEnabled(true);
Intent intent = getIntent();
// get the extra value
valuename = intent.getStringExtra("restaurantmenuname");
valueid = intent.getStringExtra("restaurantmenunameid");
valueid1 = intent.getStringExtra("idsrestaurantMenuId5");
//totalamount = intent.getStringExtra("ruppees");
Log.i("valueid",valueid);
Log.i("valuename",valuename);
Log.i("valueid1",valueid1);
// Log.i("totalamount",totalamount);
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void,Void,Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(DetaisRESTActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Android JSON Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
Toast.makeText(DetaisRESTActivity.this, "Successs", Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<ListModel>();
// Retrieve JSON Objects from the given URL address
// Log.i("123",value1);
jsonobject = JSONfunctions.getJSONfromURL("http://firstchoicefood.in/fcfapiphpexpert/phpexpert_restaurantMenuItem.php?r=" + URLEncoder.encode(valuename) + "&resid=" + URLEncoder.encode(valueid1) + "&RestaurantCategoryID=" + URLEncoder.encode(valueid) + "");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("RestaurantMenItems");
Log.i("1234",""+jsonarray);
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
ListModel sched = new ListModel();
sched.setId(jsonobject.getString("id"));
sched.setProductName(jsonobject.getString("RestaurantPizzaItemName"));
sched.setPrice(jsonobject.getString("RestaurantPizzaItemPrice"));
arraylist.add(sched);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listViewdetails);
adapter = new ListAdapterAddItems();
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
//listview.invalidateViews();
adapter.notifyDataSetChanged();
// listview.notifyAll();
listview.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3)
{
// Get Person "behind" the clicked item
ListModel p =(ListModel)listview.getItemAtPosition(position);
// Log the fields to check if we got the info we want
Log.i("SomeTag",""+p.getId());
//String itemvalue=(String)listview.getItemAtPosition(position);
Log.i("SomeTag", "Persons name: " + p.getProductName());
Log.i("SomeTag", "Ruppees: " + p.getPrice());
//count++;
//countString=String.valueOf(count);
Toast toast = Toast.makeText(getApplicationContext(),
"Item " + (position + 1),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
//Toast.makeText(getBaseContext(),
// countString, Toast.LENGTH_LONG).show();
Log.i("postititi",""+position);
// mTitleTextView.setText(countString);
Intent intent=new Intent(DetaisRESTActivity.this,QuentityActivity.class);
intent.putExtra("quentity",countString);
intent.putExtra("valueid",valueid);
intent.putExtra("valuename",valuename);
intent.putExtra("valueid1",valueid1);
intent.putExtra("id",p.getId());
intent.putExtra("name",p.getProductName());
intent.putExtra("price",p.getPrice());
startActivityForResult(intent,2);
// startActivity(intent);
}
});
}
}
// Call Back method to get the Message form other Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 2
if(requestCode==2)
{
// aa=new ArrayList();
pos=data.getStringExtra("POSITION");
message=data.getStringExtra("MESSAGE");
message1=data.getStringExtra("COUNTSTRING");
messagevaluename=data.getStringExtra("VALUENAME");
Log.i("xxxxxxxxxxx",message);
Log.i("xxxxxxxxxxx1234",pos);
Log.i("xxxxxxxxxxx5678count",message1);
Log.i("messagevaluename",messagevaluename);
//ruppees.setText(message);
mTitleTextView.setText(message1);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), message,
Toast.LENGTH_LONG).show();
Intent i=new Intent(DetaisRESTActivity.this,TotalPriceActivity.class);
i.putExtra("ruppees",message);
i.putExtra("id",pos);
i.putExtra("messagevaluename",messagevaluename);
startActivity(i);
}
});
}
}
//==========================
class ListAdapterAddItems extends ArrayAdapter<ListModel>
{
ListAdapterAddItems(){
super(DetaisRESTActivity.this,android.R.layout.simple_list_item_1,arraylist);
//imageLoader = new ImageLoader(MainActivity.this);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if(convertView == null){
LayoutInflater inflater = getLayoutInflater();
convertView = inflater.inflate(R.layout.cartlistitem, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}else{
holder = (ViewHolder)convertView.getTag();
}
holder.populateFrom(arraylist.get(position));
// arraylist.get(position).getPrice();
return convertView;
}
}
class ViewHolder {
ViewHolder(View row) {
restaurantname = (TextView) row.findViewById(R.id.rastaurantnamedetailsrestaurant);
ruppees = (TextView) row.findViewById(R.id.rastaurantcuisinedetalsrestaurant);
}
// Notice we have to change our populateFrom() to take an argument of type "Person"
void populateFrom(ListModel r) {
restaurantname.setText(r.getProductName());
ruppees.setText(r.getPrice());
}
}
//=============================================================
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_detais_rest, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
return super.onOptionsItemSelected(item);
}
}
Second activity....
package com.firstchoicefood.phpexpertgroup.firstchoicefoodin;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.bean.ListModel;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.json.JSONfunctions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URLEncoder;
import java.util.ArrayList;
public class QuentityActivity extends Activity {
String value=null;
public String TotAmt=null;
String Name;
ImageButton positive,negative;
String position;
int count = 1;
int tot_amt = 0;
public String countString=null;
String Rs,name,price;
String valueid,valueid1,valuename;
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
public TextView ruppees,submenuname,totalruppees,quantity,addtocart;
ProgressDialog mProgressDialog;
ArrayList<ListModel> arraylist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quentity);
ActionBar actionBar = getActionBar();
// Enabling Up / Back navigation
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#ff0000")));
Intent intent = getIntent();
// get the extra value
value = intent.getStringExtra("quentity");
valuename = intent.getStringExtra("valuename");
valueid = intent.getStringExtra("valueid");
valueid1 = intent.getStringExtra("valueid1");
name=intent.getStringExtra("name");
price=intent.getStringExtra("price");
position=intent.getStringExtra("id");
Log.i("valueid",valueid);
Log.i("valuename",valuename);
Log.i("valueid1",valueid1);
Log.i("name",name);
Log.i("price",price);
Log.i("id1",position);
quantity=(TextView)findViewById(R.id.rastaurantcuisinedetalsrestaurantquantity);
totalruppees=(TextView)findViewById(R.id.rastaurantnamequentitytotal1);
submenuname=(TextView)findViewById(R.id.rastaurantnamesubmenuquentity);
ruppees=(TextView)findViewById(R.id.rastaurantnamequentity1);
positive=(ImageButton)findViewById(R.id.imageButtonpositive);
negative=(ImageButton)findViewById(R.id.imageButtonnegative);
addtocart=(TextView)findViewById(R.id.textViewaddtocart);
buttonclick();
addtocart();
// value1 = intent.getStringExtra("numericitem");
// int numericvalue = intent.getIntExtra("numericitem", 11);
submenuname.setText(name);
ruppees.setText(price);
totalruppees.setText(price);
// new DownloadJSON().execute();
}
public void buttonclick(){
positive.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String getString =quantity.getText().toString();
String totalAmtString = ruppees.getText().toString();
int totAmount = Integer.parseInt(totalAmtString);
//count = Integer.parseInt(getString);
count++;
countString = String.valueOf(count);
tot_amt = totAmount * count;
TotAmt = String.valueOf(tot_amt);
totalruppees.setText(TotAmt);
quantity.setText(countString);
}
});
negative.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String getString =quantity.getText().toString();
String totalAmtString = ruppees.getText().toString();
int totAmount = Integer.parseInt(totalAmtString);
//count = Integer.parseInt(getString);
if (count > 1)
count--;
countString = String.valueOf(count);
tot_amt = totAmount * count;
TotAmt = String.valueOf(tot_amt);
totalruppees.setText(TotAmt);
quantity.setText(countString);
}
});
}
public void addtocart(){
addtocart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent();
intent.putExtra("MESSAGE",TotAmt);
intent.putExtra("POSITION",position);
intent.putExtra("COUNTSTRING",countString);
intent.putExtra("VALUENAME",valuename);
setResult(2,intent);
finish();//finishing activity
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_quentity, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I have an alert dialog that allows user to edit a TextView. Currently, once the alert dialog closes, the user has to hit the back button and then re-enter the activity for the TextView to update. I've tried many solutions on SO but none seem to work. When the user clicks 'Save Changes', the TextView should update.
Calling activity:
package com.group1.workouttracker;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.List;
public class DayActivity extends Activity {
//does not extend ListActivity, so list functions must be called by myList object
private String buttonClicked;
private String thisSummary;
private Intent intent;
DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_day);
db = DatabaseHelper.getInstance(getApplicationContext());
intent = getIntent();
buttonClicked = intent.getStringExtra("Day");
Button buttonCreateExercise = (Button) findViewById(R.id.buttonAddExercise);
buttonCreateExercise.setOnClickListener(new OnClickListenerCreateExercise(buttonClicked));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void readSummary(String buttonClicked) {
TextView textViewSummary = (TextView) findViewById(R.id.textViewSummary);
textViewSummary.setOnLongClickListener(new OnLongClickListenerEditSummary(buttonClicked));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onResume() {
super.onResume();
thisSummary = db.readSummary(buttonClicked).getSummary();
TextView summary = (TextView) findViewById(R.id.textViewSummary);
summary.setOnLongClickListener(new OnLongClickListenerEditSummary(buttonClicked));
summary.setText(thisSummary);
}
}
Alert Dialog that activates on a long press:
package com.group1.workouttracker;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.widget.EditText;
import android.widget.NumberPicker;
import android.widget.Toast;
public class OnLongClickListenerEditSummary implements View.OnLongClickListener {
Context context;
String dayClicked = "";
#Override
public boolean onLongClick(View view) {
context = view.getContext();
final DatabaseHelper db = DatabaseHelper.getInstance(context);
ObjectDay objectDay = db.readSummary(dayClicked);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View formElementsView = inflater.inflate(R.layout.edit_summary_form, null, false);
final long dayId = objectDay.getId();
final String dName = objectDay.getDayName();
final EditText editTextSummary = (EditText) formElementsView.findViewById(R.id.editTextSummary);
final CharSequence[] items = { "Edit", "Delete" };
new AlertDialog.Builder(context).setTitle("Exercise");
new AlertDialog.Builder(context)
.setView(formElementsView)
.setTitle("Edit Summary for " + dayClicked + ":")
.setPositiveButton("Save Changes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
ObjectDay objectDay = new ObjectDay();
objectDay.setId(dayId);
objectDay.setDayName(dName);
objectDay.setSummary(editTextSummary.getText().toString());
boolean updateSuccessful = DatabaseHelper.getInstance(context).updateSummary(objectDay);
if(updateSuccessful) {
Toast.makeText(context, "Summary was updated.", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(context, "Unable to update summary.", Toast.LENGTH_SHORT).show();
}
//dialog.cancel();
dialog.dismiss();
}
}).show();
return false;
}
public void editRecord(final String dName) {
final DatabaseHelper db = DatabaseHelper.getInstance(context);
ObjectDay objectDay = db.readSummary(dName);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View formElementsView = inflater.inflate(R.layout.edit_summary_form, null, false);
final EditText editTextDay = (EditText) formElementsView.findViewById(R.id.editTextSummary);
final EditText editTextSummary = (EditText) formElementsView.findViewById(R.id.editTextSummary);
editTextSummary.setText(objectDay.getSummary());
}
public OnLongClickListenerEditSummary(String dayClicked) {
this.dayClicked = dayClicked;
}
}
Edit: I was able to get this working correctly by adding the following code:
Activity:
public void passThrough(ObjectDay objDay) {
textViewSummary.setText(objDay.getSummary());
}
In .setpositive button:
((DayActivity) context).passThrough(objectDay);
Opening a dialog wont trigger the Activity's onPause/onResume (I'm not sure if that's true for dialog fragments). Instead you can apply an onDismissListener (which can be a member variable of the Activity or anonymous) to the dialog.
When the dialog is closed (by any means) you'll get some information and you can update your textfield. Alternatively you could do the same from the positive click listener.
Either
alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//UPDATE FROM HERE (call a method or manipulate an Activity member var)
}
});
OR
alert.setOnDismissListener(new OnDismissListener() {
public void onDismiss(DialogInterface dialog) {
//UPDATE FROM HERE (Check DialogInterface for positive if you want)
}
});
Edit, for your example:
class Whatever extends Activity {
private TextView mTextView;
private MyPassThroughListener mPassThroughListener = new MyPassThroughListener() {
#Override
public function passThrough(ObjectDay objDay) {
mTextView.setText(objDay.getSummary());
}
}
protected void onCreate(Bundle savedInstanceState) {
....
buttonCreateExercise.setOnClickListener(new OnClickListenerCreateExercise(mPassThroughListener ));
}
}
class OnLongClickListenerEditSummary {
MyPassThroughListener mPassThroughListener;
...
public OnLongClickListenerEditSummary (MyPassThroughListener passThroughListener) {
mPassThroughListener = passThroughListener;
}
#Override
public boolean onLongClick(View view) {
....
new AlertDialog.Builder(context)
.setPositiveButton("Save Changes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
ObjectDay objectDay = new ObjectDay();
objectDay.setId(dayId);
objectDay.setDayName(dName);
objectDay.setSummary(editTextSummary.getText().toString());
mPassThroughListener.passThrough(objectDay);
dialog.dismiss();
}
...
}
}
public interface MyPassThroughListener {
public function passThrough(ObjectDay objDay);
}