this is my main activity code.
this is kind of jumble solver Program.
Jumble helper is create to solve unjumble word.
When you enter any Unordered word it will gives correct dictionary word.
currently when I tap on any word it text converted in to voice (TTS API) instead of I want to open dictionary meaning.
now I want to add dictionary meaning from web dictionary..
how can I add word meaning??
note that I will currently call data from unix word dic.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edt_char = (EditText) findViewById(R.id.editText);
wordListView = (ListView) findViewById(R.id.word_listview);
wordListView.setOnItemClickListener(this);
tts = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int i) {
if (i != TextToSpeech.ERROR) {
tts.setLanguage(Locale.ENGLISH);
}
}
});
copyDBFileOnlyOnce();
}
public void viewOnClick(View button) {
switch (button.getId()) {
case R.id.btnGet:
String word = edt_char.getText().toString();
if (!"".equalsIgnoreCase(word) && ResourceUtil.supportedWordFormat(word)) {
new DataDictionaryTask(this, wordListView).execute(AlphabetToPrime.calcPrimeProduct(word.toLowerCase()));
} else {
((View)(wordListView.getParent())).setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), "Please enter a-z characters only", Toast.LENGTH_LONG).show();
}
hideSoftKeyboard(this);
break;
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setContentView(R.layout.activity_main);
}
#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) {
return super.onOptionsItemSelected(item);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String spk = (String)parent.getItemAtPosition(position);
Log.d("Selected text:", spk);
tts.speak(spk, TextToSpeech.QUEUE_FLUSH, null);
}
private void copyDBFileOnlyOnce()
{
prefs = getSharedPreferences("jumblehelper_pref", MODE_PRIVATE);
if (prefs.getBoolean("firstrun", true)) {
new AssetLoader(this).execute("jumblehelper.db3");
prefs.edit().putBoolean("firstrun", false).commit();
}
}
public static void hideSoftKeyboard(Activity activity) {
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}
}
Related
I'm creating a app that is for notes. I'm trying to figure out how to create a function that will delete the Note by having an option in a menu inside of the edit portion of the app that you can press and then it will delete the note. Can someone please point me in the right direction to doing something like this? I have included my code below for both my main activity Java file and my editor activity file
Main
public class MainActivity extends AppCompatActivity {
static ArrayList<String> notes = new ArrayList<>();
static ArrayAdapter arrayAdapter;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.add_note_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
super.onOptionsItemSelected(item);
if (item.getItemId() == R.id.add_note) {
// Going from MainActivity to NotesEditorActivity
Intent intent = new Intent(getApplicationContext(), NoteEditorActivity.class);
startActivity(intent);
return true;
}
return false;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = findViewById(R.id.listView);
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("com.example.notes", Context.MODE_PRIVATE);
HashSet<String> set = (HashSet<String>) sharedPreferences.getStringSet("notes", null);
if (set == null) {
notes.add("Welcome To Notes!!!!!");
} else {
notes = new ArrayList(set);
}
// Using custom listView Provided by Android Studio
arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_expandable_list_item_1, notes);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
// Going from MainActivity to NotesEditorActivity
Intent intent = new Intent(getApplicationContext(), NoteEditorActivity.class);
intent.putExtra("noteId", i);
startActivity(intent);
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
final int itemToDelete = i;
// To delete the data from the App
new AlertDialog.Builder(MainActivity.this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Are you sure?")
.setMessage("Do you want to delete this note?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
notes.remove(itemToDelete);
arrayAdapter.notifyDataSetChanged();
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("com.example.notes", Context.MODE_PRIVATE);
HashSet<String> set = new HashSet(MainActivity.notes);
sharedPreferences.edit().putStringSet("notes", set).apply();
}
}).setNegativeButton("No", null).show();
return true;
}
});
}
}
Editer
public class NoteEditorActivity extends AppCompatActivity {
int noteId;
static ArrayList<String> notes = new ArrayList<>();
#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.
if (item.getItemId() == R.id.add_note) {
}
int id = item.getItemId();
if(id == android.R.id.home){
Intent i= new Intent(this, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//To have the back button!!
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
setContentView(R.layout.activity_note_editor);
EditText editText = findViewById(R.id.editText);
Intent intent = getIntent();
noteId = intent.getIntExtra("noteId", -1);
if (noteId != -1) {
editText.setText(MainActivity.notes.get(noteId));
} else {
MainActivity.notes.add("");
noteId = MainActivity.notes.size() - 1;
MainActivity.arrayAdapter.notifyDataSetChanged();
}
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
// add your code here
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
MainActivity.notes.set(noteId, String.valueOf(charSequence));
MainActivity.arrayAdapter.notifyDataSetChanged();
// Creating Object of SharedPreferences to store data in the phone
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("com.example.notes", Context.MODE_PRIVATE);
HashSet<String> set = new HashSet(MainActivity.notes);
sharedPreferences.edit().putStringSet("notes", set).apply();
}
#Override
public void afterTextChanged(Editable editable) {
// add your code here
}
});
}
}
I have two edittexts for username and password ,I use the seterror method to show an error when both of them are empty.The problem is when the error message pops up in the second field(the password field) , part of the message is missing.This bug is there only on older devices.How do i ensure that the error does not happen in older devices.
My code:
public class SignInPage extends Activity {
EditText txtusername,txtpassword;
Button btnlogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.signinpage);
txtusername=(EditText) findViewById(R.id.txtusername);
txtpassword=(EditText) findViewById(R.id.txtpassword);
btnlogin=(Button) findViewById(R.id.btnlogin);
btnlogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(txtusername.getText().toString().trim().equals(""))
{
txtusername.setError("Username is mandatory");
txtusername.requestFocus();
}
if(txtpassword.getText().toString().trim().equals(""))
{
txtpassword.setError("Password is mandatory");
txtpassword.requestFocus();
}
else
{
Toast.makeText(getApplicationContext(),"Checking with server",Toast.LENGTH_LONG).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;
}
}
Try this it might help you
fname = FirstName.getText().toString().trim();
if(fname.isEmpty()) //&& fname.matches("[a-zA-Z ]+"))
{
FirstName.requestFocus();
FirstName.setError(Html.fromHtml("<font color='red'>Please enter the First name</font>"));
}
TextWatcher textWatcher = new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3)
{ }
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3)
{ }
#Override
public void afterTextChanged(Editable arg0)
{
if(arg0.toString().isEmpty())
{
return;
}
if (FirstName.getText() == arg0) {
Validate(FirstName);
FirstName.addTextChangedListener(textWatcher);
public void Validate(EditText et) {
et.setError(null);
}
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.
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();
First code:
package com.fshare.zsee;
public class ZSEEActivity extends TabActivity {
private WebView webview ;
private WebView webviewtwo;
private TabHost mTabHost;
private WebSettings webviewtwoSettings;
private int error;
protected void onStart() {
super.onStart();
// The activity is about to become visible.
}
protected void onStop() {
super.onStop();
// The activity is about to become visible.
}
protected void onRestart() {
super.onRestart();
}
protected void onDestroy(){
super.onDestroy();
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Activity activity = this;
mTabHost = getTabHost();
mTabHost.addTab(mTabHost.newTabSpec("tab_test1").setIndicator("Zastępstwa").setContent(R.id.tab1));
mTabHost.addTab(mTabHost.newTabSpec("tab_test2").setIndicator("Plan Lekcji").setContent(R.id.tab2));
mTabHost.addTab(mTabHost.newTabSpec("tab_test3").setIndicator("O programie").setContent(R.id.tab3));
webview = (WebView) findViewById(R.id.webView1);
webviewtwo = (WebView) findViewById(R.id.webView2);
webviewtwoSettings = webviewtwo.getSettings();
if (savedInstanceState != null){
error = savedInstanceState.getInt("webtwoerror");
webview.restoreState(savedInstanceState.getBundle("stateone"));
webviewtwo.restoreState(savedInstanceState.getBundle("statetwo"));
if(error == 1){
webviewtwoSettings.setTextSize(TextSize.NORMAL);
}
else{
webviewtwoSettings.setTextSize(TextSize.LARGER);
}
mTabHost.setCurrentTab(savedInstanceState.getInt("CURRENT_TAB"));
}
else{
webviewtwoSettings.setTextSize(TextSize.LARGER);
webview.loadUrl("http://zsee.bytom.pl/ogloszenia.php");
webviewtwo.loadUrl("http://zsee.bytom.pl/plannew/index.html");
//error = 0 ;
mTabHost.setCurrentTab(0);
}
webview.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
String summary = "<html><body><meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" ><center>Coś się zepsuło :(</center></body></html>";
webview.loadData(summary, "text/html","utf-8");
Toast.makeText(activity, "O nie! " + description, Toast.LENGTH_SHORT).show();
}
});
webviewtwo.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
webviewtwoSettings.setTextSize(TextSize.NORMAL);
String summary = "<html><body><meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" ><center>Coś się zepsuło :(</center></body></html>";
webviewtwo.loadData(summary, "text/html","utf-8");
Toast.makeText(activity, "O nie! " + description, Toast.LENGTH_SHORT).show();
error = 1 ;
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK)
{
// put your stuff here or just block the back button for perticular activity
Intent i = new Intent();
i.setAction(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_HOME);
this.startActivity(i);
}
return super.onKeyDown(keyCode, event);
}
protected void onSaveInstanceState(Bundle outState) {
Bundle outStateone = new Bundle();
Bundle outStatetwo = new Bundle();
webview.saveState(outStateone);
webviewtwo.saveState(outStatetwo);
outState.putBundle("stateone", outStateone);
outState.putBundle("statetwo", outStatetwo);
outState.putInt("CURRENT_TAB", mTabHost.getCurrentTab());
outState.putInt("webtwoerror", error);
}
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.item1:
final AlertDialog alertdialog= new AlertDialog.Builder(this).create();
alertdialog.setTitle("O Programie");
alertdialog.setMessage("Zmiany w 1.0.1: \n-Obsługa planu z dnia 17.10.2011\n-Drobne Poprawki");
alertdialog.setButton("Fajno", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
alertdialog.cancel();
}
});
alertdialog.show();
return true;
case R.id.item2:
finish();
case R.id.item3:
if(mTabHost.getCurrentTab() == 0){
webview.loadUrl("http://zsee.bytom.pl/ogloszenia.php");
}
else if(mTabHost.getCurrentTab() == 1)
{
error = 0 ;
webviewtwo.loadUrl("http://zsee.bytom.pl/plannew/index.html");
webviewtwoSettings.setTextSize(TextSize.LARGER);
}
default:
return super.onOptionsItemSelected(item);
}
}
}
And now very simple question. Why webviewtwo reload page after change orientation and webview (webView1) doesen't ? and how to prevent it? Now only webView1 doesen't reload page after change screen orientation.
Sierran
I am not sure why the first one doesn't change but adding this to my manifest inside of the activity tag worked for me
android:configChanges="orientation|keyboardHidden|keyboard"