I'm a beginner in Android Studio and Java, and I'm building an app, which contains a dialog, built using DialogFragment. Here's the code for dialog.java:
package com.dkapps.shownamenow;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatDialogFragment;
public class datatype1 extends AppCompatDialogFragment {
String type = "";
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setNeutralButton("Regular Fraction", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
type = "frac";
}
});
builder.setNeutralButton("Whole Number", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
type = "whole";
}
});
builder.setNeutralButton("Mixed Fraction", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
type = "mixed";
}
});
return builder.create();
}
}
Now, I have a textview in my activity_main with the id 'type'. I want this dialog to set the text of that textview to the value of the string type. How do I do that?
I'd be grateful if you'd provide me some code.
You could create a method inside your activity to change the TextView's content, and call it in each of the buttons onClick methods.
Here is a code sample:
// inside you activity
public setText(String text){
findViewById(R.id.type).setText(text);
}
// onClick methods
#Override
public void onClick(DialogInterface dialog, int which) {
((MainActivity)getActivity()).setText("whole")
// change "whole" with the value of the string suitable for each button
}
You can get rid of the variable type, if you do not need it elsewhere
You could get the textView of your activity with findViewById()
private TextView typeFromActivity;
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
...
typeFromActivity = (TextView) findViewById(R.id.type);
type = typeFromActivity.getText().toString();
...
return builder.create();
}
Related
My program opens a DialogFragment class while running in MainActivity.java
I want to be able to click on the "neutral button" of that dialog and open a new activity, SensorDataDisplay.java
I am having trouble finding the right way to reference the Context in my button's onClick.
package com.august.customtisensortagclient;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import java.util.ArrayList;
public class GetInfoDialog extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final String thisWhichGetInfoDialog = ((MainActivity)getActivity()).getWhichGetInfoDialog();
final ArrayList<String> thisScannedDevicesArrayList =
((MainActivity)getActivity()).getScannedDevicesArrayList();
final int thisIsInLeftConnectedDeviceDisplay = ((MainActivity)getActivity()).getIsInLeftConnectedDeviceDisplay();
final int thisIsInRightConnectedDeviceDisplay = ((MainActivity)getActivity()).getIsInRightConnectedDeviceDisplay();
int thisIsInThisConnectedDeviceDisplay = 0;
if (thisWhichGetInfoDialog == "Left") {
thisIsInThisConnectedDeviceDisplay = thisIsInLeftConnectedDeviceDisplay;
} else if (thisWhichGetInfoDialog == "Right")
thisIsInThisConnectedDeviceDisplay = thisIsInRightConnectedDeviceDisplay;
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(thisWhichGetInfoDialog + " Sensor Info");
builder.setMessage("MAC Address: " + thisScannedDevicesArrayList.get(thisIsInThisConnectedDeviceDisplay));
builder.setNeutralButton("View Data", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent myIntent = new Intent(?????, SensorDataDisplay.class);
myIntent.putExtra("key", "TEST VALUE"); //Optional parameters
?????.startActivity(myIntent);
}
});
builder.setNegativeButton("Done", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
return builder.create();
}
}
DialogFragment has getActivity() and getContext() methods (which it inherits from Fragment), both will work in your case. If you're having trouble accessing these methods from the anonymous class (which shouldn't be the case), you can use the GetInfoDialog.this.getActivity() syntax.
getActivity() returns the Activity the fragment is attached to
builder.setNeutralButton("View Data", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent myIntent = new Intent(getActivity(), SensorDataDisplay.class);
myIntent.putExtra("key", "TEST VALUE"); //Optional parameters
getActivity().startActivity(myIntent);
}
});
Edit: I've made some updates to this ever since I got responses to this thread. Here's the new thread:
I've been making an Android application where you would save your favorite websites. Here is what I got for the code in the file 'MainActivity.java' so far:
package cory.assignment.favoritewebsitesapp;
import java.util.ArrayList;
import java.util.Collections;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
public class MainActivity extends ListActivity {
private static final String SEARCHES = "searches";
private EditText queryEditText;
private EditText tagEditText;
private SharedPreferences savedSearches;
private ArrayList<String> tags;
private ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
queryEditText = (EditText) findViewById(R.id.queryEditText);
tagEditText = (EditText) findViewById(R.id.tagEditText);
savedSearches = getSharedPreferences(SEARCHES, MODE_PRIVATE);
tags = new ArrayList<String>(savedSearches.getAll().keySet());
Collections.sort(tags, String.CASE_INSENSITIVE_ORDER);
adapter = new ArrayAdapter<String>(this, R.layout.list_item, tags);
setListAdapter(adapter);
ImageButton saveButton = (ImageButton) findViewById(R.id.saveButton);
saveButton.setOnClickListener(saveButtonListener);
getListView().setOnItemClickListener(itemClickListener);
getListView().setOnItemLongClickListener(itemLongClickListener);
}
public OnClickListener saveButtonListener = new OnClickListener()
{
#Override
public void onClick(View v)
{
if (queryEditText.getText().length() > 0 && tagEditText.getText().length() > 0)
{
addTaggedSearch(queryEditText.getText().toString(), tagEditText.getText().toString());
queryEditText.setText("");
tagEditText.setText("");
((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(tagEditText.getWindowToken(), 0);
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage(R.string.missingMessage);
builder.setPositiveButton(R.string.OK, null);
AlertDialog errorDialog = builder.create();
errorDialog.show();
}
}
};
private void addTaggedSearch(String query, String tag)
{
SharedPreferences.Editor preferencesEditor = savedSearches.edit();
preferencesEditor.putString(tag, query);
preferencesEditor.apply();
if (!tags.contains(tags))
{
tags.add(tag);
Collections.sort(tags, String.CASE_INSENSITIVE_ORDER);
adapter.notifyDataSetChanged();
}
}
OnItemClickListener itemClickListener = new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
String tag = ((TextView) view).getText().toString();
String urlString = getString(R.string.searchURL) + Uri.encode(savedSearches.getString(tag, ""), "UTF-8");
Intent webIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(urlString));
startActivity(webIntent);
}
};
OnItemLongClickListener itemLongClickListener =
new OnItemLongClickListener()
{
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id)
{
final String tag = ((TextView) view).getText().toString();
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(getString(R.string.shareEditDeleteTitle, tag));
builder.setItems(R.array.dialog_items, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
switch (which)
{
case 0:
shareSearch(tag);
break;
case 1:
tagEditText.setText(tag);
queryEditText.setText(savedSearches.getString(tag, ""));
break;
case 2:
deleteSearch(tag);
break;
}
}
}
);
builder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
dialog.cancel();
}
}
);
builder.create().show();
return true;
}
};
private void shareSearch(String tag)
{
String urlString = getString(R.string.searchURL) + Uri.encode(savedSearches.getString(tag, ""), "UTF-8");
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.shareSubject));
shareIntent.putExtra(Intent.EXTRA_TEXT, getString(R.string.shareMessage, urlString));
shareIntent.setType("text/plain");
startActivity(Intent.createChooser(shareIntent, getString(R.string.shareSearch)));
}
private void deleteSearch(final String tag)
{
AlertDialog.Builder confirmBuilder = new AlertDialog.Builder(this);
confirmBuilder.setMessage(getString(R.string.confirmMessage, tag));
confirmBuilder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
dialog.cancel();
}
}
);
confirmBuilder.setPositiveButton(getString(R.string.delete), new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
tags.remove(tag);
SharedPreferences.Editor preferencesEditor = savedSearches.edit();
preferencesEditor.remove(tag);
preferencesEditor.apply();
adapter.notifyDataSetChanged();
}
}
);
confirmBuilder.create().show();
}
}
However, I have got the errors for the code with certain lines:
Line 79: OK cannot be resolved or is not a field
Line 146: cancel cannot be resolved or is not a field
Line 177: cancel cannot be resolved or is not a field
Line 186: delete cannot be resolved or is not a field
The link below shows what I have for activity_main.xml:
Click here for the image
What could be wrong with those lines? Something isn't right with those lines as they are related to the info on this page.
I am also using the proram Eclipse Java EE IDE for Web Developers to make this as well in case you wanted to know what program I was using. I'm also using API 18 to work on this as well.
If you want to take a look at the other files, then let me know.
I know that some of them are strings that I need to make for the strings.xml file, but would their values have to be messages like "This file is missing", or would they have to be special integers?
They need to be in res/values/strings.xml, yes.
Those values are compiled into "special integers" for you and are accessible by R.string.xxxxx.
I imagine that solves the majority of the errors saying "cannot be resolved or is not a field".
DialogInterference cannot be resolved to a type
Did you mean DialogInterface?
The method deleteSearch(string) from the type MainActivity refers to the missing type string
Look at this line. What is string?
private void deleteSearch(final string tag)
So upon examination, I found out that the other lines did need strings after all despite what it said about certain R.string codes on this page for 'cancel' and 'OK'. So why did 'cancel' and 'OK' need their own strings in strings.xml?
I am trying to get a value that user enters into a Dialog, using the recommended DialogFragment class for it, the Dialog constructs and runs fine, but I cannot return the value of the EditText parameter to the parent class, without get a NullPointerException.
My DialogHost class, this constructs, returns and links the parent to its buttons.
package jo.app.co;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
public class DialogHost extends DialogFragment {
public interface NoticeDialogListener {
public void onDialogPositiveClick(DialogFragment dialog);
public void onDialogNegativeClick(DialogFragment dialog);
}
NoticeDialogListener mListener;
#override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (NoticeDialogListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString());
}
}
#override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
builder.setView(inflater.inflate(R.layout.dialog_add, null))
.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#override
public void onClick(DialogInterface dialog, int id) {
mListener.onDialogPositiveClick(DialogHost.this);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
DialogHost.this.getDialog().cancel();
}
});
return builder.create();
}
}
This is my MainActivity class showing the dialog
package jo.app.co;
import android.app.DialogFragment;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.widget.EditText;
public class MainActivity extends FragmentActivity implements DialogHost.NoticeDialogListener {
#override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showNoticeDialog();
}
public void showNoticeDialog() {
DialogFragment dialog = new DialogHost();
dialog.show(getFragmentManager(), "DialogHost");
}
#override
public void onDialogPositiveClick(DialogFragment dialog) {
EditText myText = (EditText) findViewById(R.id.item_added);
try {
Log.d ("IN TRY", myText.getText().toString());
}
catch (Exception e) {
Log.e ("IN CATCH", e.toString());
}
}
#override
public void onDialogNegativeClick(DialogFragment dialog) {
Log.d ("INMAIN", "REACHED NEG");
}
}
Thisthe layout of my Dialog for reference.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<EditText
android:id="#+id/item_added"
android:inputType="text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginBottom="4dp"
android:hint="#string/hint_add_item" />
</LinearLayout>
There seems to be problem with the way you are referring to the edit text. You need to get it from the view you inflated Please try the below code which adds all functionality in your main activity itself. If you want you can adapt to your case with a separate class:
public void showNoticeDialog() {
public String inputvalue;
LayoutInflater inflater = LayoutInflater.from(this);
final View textenter = inflater.inflate(R.layout.dialog_add, null)
final EditText userinput = (EditText) textenter.findViewById(R.id.item_added);
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(textenter)
.setTitle("Your title");
builder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#override
public void onClick(DialogInterface dialog, int id) {
inputvalue = userinput.getText().toString();
// Do something with value in inputvalue
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog dialog = builder.create();
builder.show();
}
For alert dialog , you need to inflate an xml, only if you are planning to have multiple views like more than 1 edittext in that dialog. If you plan to have only 1 edittext as in your example, you dont need an xml and you can directly define an edittext and set it as the view of the alert dialog.
final EditText userinput = new EditText(context);
builder.setView(userinput);
I just picked up the android SDK and eclipse and decided to write a simple dialog that pops up when you click a button, however I found out that the showDialog() method has been deprecated and that the DialogFragment was the best way to go about making one, so here it is:
package net.learn2develop.dialog;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.view.View;
import android.widget.Button;
public class DialogWindow extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_window);
Button btn = (Button) findViewById(R.id.btn_dialog);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
class MyDialog extends DialogFragment {
FragmentManager fm = getFragmentManager();
public MyDialog() {
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
//using the builder class
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Simple Dialog")
.setPositiveButton("nothing", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Toast.makeText(getBaseContext(), "ok then", Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Toast.makeText(getBaseContext(), "cancel", Toast.LENGTH_SHORT).show();
}
});
return builder.create();
}
}
MyDialog md = new MyDialog();
md.show(md.fm, "dialog");
}
});
}
}
The Debugger shows the error at:
md.show(md.fm, "dialog");
On further inspection, the fm variable is null according to the variables tab in the debugger, why is this so and is there a more efficient solution to this? I am seriously new to android, sorry if this is an easy question.
You should use an AlertDialog in this case, not a DialogFragment. Here is how I would do it:
public class DialogWindow extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_window);
Button btn = (Button) findViewById(R.id.btn_dialog);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
createDialog.show();
}
});
}
public Dialog createDialog() {
//using the builder class
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Simple Dialog")
.setPositiveButton("nothing", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//getBaseContext() is not advised (I can't remember why right now but I know I read it. You may want to read more that method but for now getActivity will work for your Toast.
//Toast.makeText(getActivity(), "ok then", Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Toast.makeText(getActivity(), "cancel", Toast.LENGTH_SHORT).show();
}
});
return builder.create();
}
}
DialogFragments should be used in conjunction with other Fragments, in the case of a single activity it would be best to use an AlertDialog.
I have a Android Application which is basically uses WebView for all interaction..
How can i access (read) Cookies which are created in WebView (if someone logs in) and than store them somewhere, maybe in SharedPreferences, so that later i can use them.
For example.. on quitting the application .. i can say "Thank Mr.XYZ,do u really want to quit"
Here is my code...
package com.example.hellowebview;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.webkit.CookieSyncManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class HelloWebView extends Activity {
WebView webview;
private class HelloWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url) {
CookieSyncManager.getInstance().sync();
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
webview = (WebView) findViewById(R.id.webview);
webview.setWebViewClient(new HelloWebViewClient(
));
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("http://www.mysite.com/mobile");
}
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Thank <<Name Cookie value from Webview >>>,do u really want to quit?")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
To work with WebView cookies, you can use CookieManager which has some getter and setter methods for you.
http://developer.android.com/reference/android/webkit/CookieManager.html