how to create and save edittext from alert? - java

I am still trying to learn java android so I am sure this is easy but I am trying to save the text from an alert started from an onclicklistener using the edit text to rename a button (tabButton). Do I have to create a seperate layout or will this work? I am getting an error at
final EditText input = new EditText(this);
Like I said I am still learning so a good explanation is appreciated. Here is my src so far.
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Tab buttons controlled
final Button getTabButton = (Button) findViewById(R.id.tab1);
final AlertDialog.Builder alert = new AlertDialog.Builder(this);
getTabButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Tab1 button was clicked.
alert.setTitle("Title");
alert.setMessage("Message");
// Set an EditText view to get user input
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Editable tabname = input.getText();
// Do something with value!
tabname =
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
}
});
}
#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);
}
}

Try this way,hope this will help you to solve your problem.
public class MainActivity extends Activity {
private Button getTabButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getTabButton = (Button) findViewById(R.id.tab1);
getTabButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
alert.setTitle("Title");
alert.setMessage("Message");
final EditText input = new EditText(MainActivity.this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Toast.makeText(MainActivity.this,input.getText().toString(),Toast.LENGTH_SHORT).show();
((Button)view).setText(input.getText());
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
}
});
}
#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);
}
}

Try like below:
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
getTabButton.settext(input.getText().toString());
}
});

Related

Onclick listener for navigation bar

I have developed an android application using java and android studio. But when I click the items in the navigation drawer, I expect it to display a dialog, but nothing happens. Also when I try to setText in the drawer, the application crashes. I'm new to android development. Please, I would greatly appreciate help.
Below is my code:
private TextView name;
public TextView email;
public TextView contact;
private DrawerLayout drawerLayout;
AlertDialog.Builder builder;
private ActionBarDrawerToggle actionBarDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawerLayout=(DrawerLayout) findViewById(R.id.drawer);
builder=new AlertDialog.Builder(MainActivity.this);
name=(TextView) findViewById(R.id.myname);
email=(TextView) findViewById(R.id.myemail);
contact=(TextView) findViewById(R.id.mycontact);
actionBarDrawerToggle=new ActionBarDrawerToggle(this, drawerLayout,R.string.open,R.string.close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//RECEIVING THE INTENT
/* Get values from Intent
Intent intent = getIntent();
String myname = intent.getStringExtra("dname");
String myemail = intent.getStringExtra("demail");
String mycontact = intent.getStringExtra("dcontact");
name.setText(myname);
email.setText(myemail);
contact.setText(mycontact);
builder.setTitle("Log In Successful");
builder.setMessage("Welcome, "+myname);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Toast.makeText(getApplicationContext(),"Clock Out Cancelled",Toast.LENGTH_SHORT).show();
}
});
AlertDialog alertDialog=builder.create();
alertDialog.show();*/
//name.setText(response);
/*try {
JSONObject jsonObject = new JSONObject(fname);
String fstname=jsonObject.getString("clockTym");
String lstname=jsonObject.getString("timediff");
String demail=jsonObject.getString("penalty");
String dcontact=jsonObject.getString("tot_penalty");
name.setText(fstname+" "+lstname);
email.setText(demail);
contact.setText(dcontact);
} catch (JSONException e) {
e.printStackTrace();
}*/
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(actionBarDrawerToggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.cin){
// Handle the camera action
builder.setTitle("Log In Successful");
builder.setMessage("Welcome, ");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Toast.makeText(getApplicationContext(),"Clock Out Cancelled",Toast.LENGTH_SHORT).show();
}
});
AlertDialog alertDialog=builder.create();
alertDialog.show();
} else if (id == R.id.db) {
builder.setTitle("Log In Successful");
builder.setMessage("Welcome, ");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Toast.makeText(getApplicationContext(),"Clock Out Cancelled",Toast.LENGTH_SHORT).show();
}
});
AlertDialog alertDialog=builder.create();
alertDialog.show();
} else if (id == R.id.permit) {
builder.setTitle("Log In Successful");
builder.setMessage("Welcome, ");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Toast.makeText(getApplicationContext(),"Clock Out Cancelled",Toast.LENGTH_SHORT).show();
}
});
AlertDialog alertDialog=builder.create();
alertDialog.show();
} else if (id == R.id.cout) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
You not initializing the navigation drawer which actually contains the list item though you already have onNavigationItemSelected listener so inside oncreate initialize the navigation view and attach the listener like
NavigationView navView = (NavigationView) findViewById(R.id.your_nav_id);
navView.setNavigationItemSelectedListener(this);

How to get Background from another Activity?

I want to change the background-color of another Activity (start) in my Settings-Activity (choose between different colors, sounds etc.).
How can I change the color of another Activity?
I tried to get the Background from my start-Activity (id:start) with:
final RelativeLayout background = (RelativeLayout) findViewById(R.id.start);
but it seems it doesn´t work.
Full Code of the Settings-Activity:
public class activity_settings extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity_settings);
ColorChange();
}
public void ColorChange() {
final RelativeLayout background = (RelativeLayout) findViewById(R.id.start);
final RadioButton ChangeToBlue = (RadioButton) findViewById(R.id.button_blue);
final RadioButton ChangeToRed = (RadioButton) findViewById(R.id.button_red);
final Button button_save = (Button) findViewById(R.id.button_save);
button_save.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
ChangeOption(background);
}
});
ChangeToBlue.setOnCheckedChangeListener(new RadioButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
ChangeToBlue(background);
}
});
ChangeToRed.setOnCheckedChangeListener(new RadioButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
ChangeToRed(background);
}
});
}
public void ChangeOption(RelativeLayout background) {
if (background.isEnabled()) {
background.setEnabled(false);
} else {
background.setEnabled(true);
}
}
public void ChangeToBlue(RelativeLayout background) {
background.setBackgroundColor(Color.BLUE);
background.invalidate();
}
public void ChangeToRed(RelativeLayout background) {
background.setBackgroundColor(Color.RED);
background.invalidate();
}
#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_activity_settings, 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);
}}
Save color code i.e. #F0F0F0 from your setting-activity in a sharedPreference and get this value in onCreate() of activity in which you want to set background.

eclipse android application syntax error

i just started to use eclipse, and im trying to do my first android application. But apparently something is wrong with my syntax error , and i dont know how can i fix it or where did i do wrongly. so i hope someone here can help me. Thanks :) pardon me for my bad english.
Those underlined in red are errors but i dont know how can i fix them.
starts below here
Here is my .java
public class Category extends Activity { <---(**this sign is underlined in red**)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_category);
Button switchButton = (Button) findViewById(R.id.button1);
switchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Category.this, Cake.class);
startActivity(intent);
Button switchButton = (Button) findViewById(R.id.button2);
switchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Category.this, Cookie.class);
startActivity(intent);
};
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.category, 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);
} ^
(**this sign is underlined in red**)
};
Unfortunately you're trying to initialize your button listener in another button listener. That's wrong.
Corrected:
Button switchButton = (Button) findViewById(R.id.button1);
switchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Category.this, Cake.class);
startActivity(intent);
};
});
Button switchButton2 = (Button) findViewById(R.id.button2);
switchButton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Category.this, Cookie.class);
startActivity(intent);
};
});

Creating DialogFragment with EditText

I'm new to android, started it about a month ago, and now I'm trying to make a "Shopping List" app for the sake of practice. In this app I have a ListView, where user can insert items via EditText above that ListView. When user longClick on item, ContextMenu with "Edit", "Delete" and "Mark" fields appears. I have already made "Delete" button work, but I still have problems with "Edit" function. To make this function work I created DialogFragment class, so when user presses the "Edit" button, this DialogFragment appears. This DF has EditText field, where we enter data we want to change. Here is DialogFragment class code:
public class AlertEdit extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder bd = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
bd.setView(inflater.inflate(R.layout.alert, null))
.setTitle("Edit")
.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
((MyActivity)getActivity()).doPositiveClick();
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
((MyActivity)getActivity()).doNegativeClick();
}
});
return bd.create();
}
as you can see, we have positive button here, which calls doPositiveClick method from MyActivity, which appears to be the main activity.
.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
((MyActivity)getActivity()).doPositiveClick();
}
So, here is the MyActivity class code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
lw = (ListView) findViewById(R.id.listView);
edtxt = (EditText) findViewById(R.id.editText);
alertEd = (EditText) findViewById(R.id.alertEdit);
goods = new ArrayList<String>();
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, goods);
lw.setAdapter(adapter);
lw.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View v,
int position, long id) {
}
});
registerForContextMenu(lw);
edtxt.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction()== KeyEvent.ACTION_DOWN) {
if (keyCode == KeyEvent.KEYCODE_ENTER) {
goods.add(0, edtxt.getText().toString());
adapter.notifyDataSetChanged();
edtxt.setText("");
return true;
}
}
return false;
}
});
}
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo info){
super.onCreateContextMenu(menu, v, info);
getMenuInflater().inflate(R.menu.actions, menu);
}
public boolean onContextItemSelected(MenuItem item) {
position = (int) info.id;
switch (item.getItemId()) {
case R.id.cnt_mnu_delete:
goods.remove(position);
adapter.notifyDataSetChanged();
return true;
case R.id.cnt_mnu_edit:
}
return super.onContextItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.my, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void doPositiveClick()
{
}
public void doNegativeClick()
{
}
public void showDialog()
{
DialogFragment frag = new AlertEdit();
frag.show(getFragmentManager(), "edit");
}
}
My problem is that I have no idea how to create that Edit function. I tryied to use AdapterContextMenuInfo, but it works only in onContextItemSelected method, because it requires and Item to work with. Hope you help me and sorry for the possible lack of information, ask me any additional questions please.
P.S. I'm trying to make this dialog for almost two weeks already and I'm really frustrated because of that.
I'm using this method - it's simple and you may adapt it to your needs:
First of all make an interface to handle your result, for example:
public interface OnDialogResultListener {
public void onDialogResult(String result);
}
Then use your dialog with additional view, like this:
public void showDialogAndGetResult(final int title, final String message, final String initialText, final OnDialogResultListener listener) {
// additional View - use appropriate View to your needs:
final EditText editText = new EditText(this);
editText.setText(initialText);
new AlertDialog.Builder(MainActivity.this)//
.setTitle(title)//
.setMessage(message)//
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (listener != null) {
listener.onDialogResult(editText.getText().toString());
}
}
})//
.setNegativeButton(android.R.string.cancel, null)//
.setView(editText)//
.show();
}
At last implement this interface in your activity:
public class YourActivity Extends Activity implements OnDialogResultListener{
...
#Override
public void onDialogResult(String result) {
//do what you need
}
...
}
Edit:
You may replace EditText by any View, including Layouts.
Still you may use the same scheme to return result from your DialogFragment descendant - just pass OnDialogResultListener in constructor or initializing method. I would say AlertDialog is more lightweight and DialogFragment allows more control and you may use both according to your needs.

Not able to link between two activities even after the code written are same throughout

These are two activities which are linked between each other but those are not working
and i have provided method name in xml file as onClick="menu" for both the buttons and the method over here
public class Welcome extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcome);
/**Intent i = new Intent(this,Menup.class);
finish();
startActivity(i);*/
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.welcome, menu);
return true;
}
public void menu(View v)
{
finish();
Intent i = new Intent(this,Menup.class);
startActivity(i);
}
}
it will be moved to the next activity name and code below
public class Menup extends Activity {
Button route,map,ticket;
TextView bal;
String time,src,des,clas,journey,noa,noc,amount;
int itime,old=50,amt,camt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menup);
bal=(TextView)findViewById(R.id.textView1);
//getting the values
Intent i=getIntent();
time=i.getExtras().getString("time");
itime=Integer.valueOf(time);
src=i.getExtras().getString("src");
des=i.getExtras().getString("des");
clas=i.getExtras().getString("class");
journey=i.getExtras().getString("journey");
noa=i.getExtras().getString("noa");
noc=i.getExtras().getString("noc");
amount=i.getExtras().getString("amount");
camt=Integer.valueOf(amount);
route=(Button)findViewById(R.id.imageButton1);
map=(Button)findViewById(R.id.imageButton2);
ticket=(Button)findViewById(R.id.imageButton3);
route.getBackground().setAlpha(0);
map.getBackground().setAlpha(0);
ticket.getBackground().setAlpha(0);
amt=old-camt;
bal.setText("Current Balance "+amt);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menup, menu);
return true;
}
public void toroute(View v)
{
Intent r = new Intent(Menup.this,Route.class);
startActivity(r);
}
public void tomap(View v)
{
Intent m = new Intent(Menup.this,Map.class);
startActivity(m);
}
public void toticket(View v)
{
Intent d=new Intent(Menup.this,Tick.class);
d.putExtra("noa",noa);
d.putExtra("noc",noc);
d.putExtra("src",src);
d.putExtra("des",des);
d.putExtra("class", "Class I");
d.putExtra("journey", "Single");
d.putExtra("amount", amount);
d.putExtra("time", itime);
startActivity(d);
}
#Override
public void onBackPressed()
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Exit");
builder.setMessage("Are you sure , you want to exit Ticketwala?");
builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Do nothing but close the dialog
finish();
System.exit(0);
dialog.dismiss();
}
});
builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Do nothing
dialog.dismiss();
}
}).show();
}
}
You don't have to "finish()" your activity Welcome before starting the next activity. But if you must, then put it after startActivity();

Categories

Resources