I have been struggling with an issue in a note application i have been building with the help of a tutorial series. I just created a dialog allowing the user to change the category of a note but the new category is lost whenever the orientation is changed. as instructed by tutorial i override onSavedInstance to save information first but for some reason is not solved code below:
package com.workingprogess.notebook;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
public class NoteEditFragment extends Fragment {
private ImageButton noteCatButton;
private EditText title;
private EditText message;
private Button saveButton;
private Note.Category savedButtonCategory;
private AlertDialog categoryDialogObject;
private AlertDialog confirmDialogObject;
private static final String MODIFIED_CATEGORY="Modified Category";
public NoteEditFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if(savedInstanceState!=null){
savedButtonCategory = (Note.Category) savedInstanceState.get(MODIFIED_CATEGORY);
}
//grab layout and assign to view so that we may access widgets
View fragmentLayout = inflater.inflate(R.layout.fragment_note_edit, container, false);
//grab widget references
title = (EditText) fragmentLayout.findViewById(R.id.editNoteTitle);
message = (EditText) fragmentLayout.findViewById(R.id.editMessage);
noteCatButton = (ImageButton) fragmentLayout.findViewById(R.id.editNoteButton);
saveButton = (Button) fragmentLayout.findViewById(R.id.saveNoteButton);
//populate with note data
Intent intent = getActivity().getIntent();
title.setText(intent.getExtras().getString(MainActivity.NOTE_TITLE_EXTRA));
message.setText(intent.getExtras().getString(MainActivity.NOTE_MESSAGE_EXTRA));
if(savedButtonCategory !=null){
Log.d("not null","the new image should be carried over");
noteCatButton.setImageResource(Note.categoryToDrawable(savedButtonCategory));
} else {
Note.Category noteCat = (Note.Category) intent.getSerializableExtra(MainActivity.NOTE_CATEGORY_EXTRA);
savedButtonCategory = noteCat;
noteCatButton.setImageResource(Note.categoryToDrawable(noteCat));
Log.e("null","pull from intent" );
}
//set onclick listeners
buildCategoryDialog();
noteCatButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
categoryDialogObject.show();
}
});
buildConfirmDialog();
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
confirmDialogObject.show();
}
});
// Inflate the layout for this fragment
return fragmentLayout;
}
//save info before orientation change.
#Override
public void onSaveInstanceState(Bundle savedInstanceState){
super.onSaveInstanceState(savedInstanceState);
Log.d("save","info is saved");
savedInstanceState.putSerializable(MODIFIED_CATEGORY, savedButtonCategory);
}
//build pop uo dialog to change note info
private void buildCategoryDialog(){
final String[] categories = new String[]{"Personal","Technical","Quote","Finance"};
final AlertDialog.Builder categoryBuilder = new AlertDialog.Builder(getActivity());
categoryBuilder.setTitle("Choose Note Type");
categoryBuilder.setSingleChoiceItems(categories, 0, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int item) {
switch (item){
case 0:
savedButtonCategory= Note.Category.PERSONAL;
noteCatButton.setImageResource(R.drawable.p_icon);
break;
case 1:
savedButtonCategory=Note.Category.TECHNICAL;
noteCatButton.setImageResource(R.drawable.t_icon);
break;
case 2:
savedButtonCategory=Note.Category.QUOTE;
noteCatButton.setImageResource(R.drawable.q_icon);
break;
case 3:
savedButtonCategory=Note.Category.FINANCE;
noteCatButton.setImageResource(R.drawable.f_icon );
break;
}
categoryDialogObject.cancel();
}
});
categoryDialogObject=categoryBuilder.create();
}
private void buildConfirmDialog(){
final AlertDialog.Builder confirmBuilder = new AlertDialog.Builder(getActivity());
confirmBuilder.setTitle("are you sure?");
confirmBuilder.setMessage("are you sure you want to save this note");
confirmBuilder.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Log.d("Save Note","Note title " + title.getText()+ "Note message "
+ message.getText()+" note category" + savedButtonCategory);
Intent intent = new Intent(getActivity(),MainActivity.class);
startActivity(intent);
}
});
confirmBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
savedButtonCategory=Note.Category.TECHNICAL;
}
});
confirmDialogObject = confirmBuilder.create();
}
}
Open your application Manifest file and for particular activity, add this code:
<activity
android:name=".MainActivity" //Activity where the problem is occuring
android:configChanges="screenLayout|orientation|screenSize">
Its better to add this "android:configChanges" to every activity to maintain data state even if orientation changes.
Have you checked if onSaveInstanceState is actually getting called? This callback will only be called if the Activity holding the fragment is getting destroyed. So, first check if your Activity is getting destroyed or not.
Related
after fixing the null pointer exception of a previous question, (Not sure if posting a different question for the same code is okay, do let me know if it is not) I've come across a new problem. When I try passing the date variable from this first activity to another, it is always empty. I've also tried just setting a public getter or the variable and it is also empty. However, using a toast to check within the class shows that the variable does indeed contain the date. I am trying to pass the date class to be added into a database by the other classes in the application package. Any help would be much appreciated.
CalendarActivity.java
package com.example.zaphk.studenthelperapplication3.calendar;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.CalendarView;
import android.widget.Toast;
import com.example.zaphk.studenthelperapplication3.R;
public class CalendarActivity extends AppCompatActivity {
public static final String EXTRA_TEXT = "com.example.zaphk.studenthelperapplication3";
private static final String TAG = "CalendarActivity";
private CalendarView mCalendarView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calendar_layout);
mCalendarView = (CalendarView) findViewById(R.id.calendarView);
mCalendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
#Override
public void onSelectedDayChange(CalendarView CalendarView, int year, int month, int dayOfMonth) {
String date = year + "/" + month + "/"+ dayOfMonth ;
Log.d(TAG, "onSelectedDayChange: yyyy/mm/dd:" + date);
Intent intent = new Intent(CalendarActivity.this,CalendarEvent.class);
intent.putExtra(Intent.EXTRA_TEXT,date);
startActivity(intent);
Toast.makeText(CalendarActivity.this,date,Toast.LENGTH_SHORT).show();
}
});
}
}
The class I am trying to receive it from : CalendarEvent.java
package com.example.zaphk.studenthelperapplication3.calendar;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import com.example.zaphk.studenthelperapplication3.calendar.database.Calendar;
import com.example.zaphk.studenthelperapplication3.calendar.database.CalendarAdapter;
import com.example.zaphk.studenthelperapplication3.calendar.database.Calendar_DbHelper;
import com.example.zaphk.studenthelperapplication3.utils.MyDividerItemDecoration;
import com.example.zaphk.studenthelperapplication3.utils.RecyclerTouchListener;
import com.example.zaphk.studenthelperapplication3.R;
public class CalendarEvent extends AppCompatActivity {
private CalendarAdapter mAdapter;
private List<Calendar> notesList = new ArrayList<>();
private CoordinatorLayout coordinatorLayout;
private RecyclerView recyclerView;
private TextView noNotesView;
Intent intent = getIntent();
public String date;
private Calendar_DbHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
intent = getIntent();
date = intent.getStringExtra(CalendarActivity.EXTRA_TEXT);
setContentView(R.layout.activity_notes);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
coordinatorLayout = findViewById(R.id.coordinator_layout);
recyclerView = findViewById(R.id.recycler_view);
noNotesView = findViewById(R.id.empty_notes_view);
db = new Calendar_DbHelper(this);
notesList.addAll(db.getAllNotes());
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showNoteDialog(false, null, -1);
}
});
mAdapter = new CalendarAdapter(this, notesList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.addItemDecoration(new MyDividerItemDecoration(this, LinearLayoutManager.VERTICAL, 16));
recyclerView.setAdapter(mAdapter);
toggleEmptyNotes();
/**
* On long press on RecyclerView item, open alert dialog
* with options to choose
* Edit and Delete
* */
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(this,
recyclerView, new RecyclerTouchListener.ClickListener() {
#Override
public void onClick(View view, final int position) {
}
#Override
public void onLongClick(View view, int position) {
showActionsDialog(position);
}
}));
}
/**
* Inserting new note in db
* and refreshing the list
*/
private void createNote(String note) {
// inserting note in db and getting
// newly inserted note id
long id = db.insertNote(note);
// get the newly inserted note from db
Calendar n = db.getNote(id);
if (n != null) {
// adding new note to array list at 0 position
notesList.add(0, n);
// refreshing the list
mAdapter.notifyDataSetChanged();
toggleEmptyNotes();
}
}
/**
* Updating note in db and updating
* item in the list by its position
*/
private void updateNote(String note, int position) {
Calendar n = notesList.get(position);
// updating note text
n.setNote(note);
// updating note in db
db.updateNote(n);
// refreshing the list
notesList.set(position, n);
mAdapter.notifyItemChanged(position);
toggleEmptyNotes();
}
/**
* Deleting note from SQLite and removing the
* item from the list by its position
*/
private void deleteNote(int position) {
// deleting the note from db
db.deleteNote(notesList.get(position));
// removing the note from the list
notesList.remove(position);
mAdapter.notifyItemRemoved(position);
toggleEmptyNotes();
}
/**
* Opens dialog with Edit - Delete options
* Edit - 0
* Delete - 0
*/
private void showActionsDialog(final int position) {
CharSequence colors[] = new CharSequence[]{"Edit", "Delete"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose option");
builder.setItems(colors, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (which == 0) {
showNoteDialog(true, notesList.get(position), position);
} else {
deleteNote(position);
}
}
});
builder.show();
}
/**
* Shows alert dialog with EditText options to enter / edit
* a note.
* when shouldUpdate=true, it automatically displays old note and changes the
* button text to UPDATE
*/
private void showNoteDialog(final boolean shouldUpdate, final Calendar note, final int position) {
LayoutInflater layoutInflaterAndroid = LayoutInflater.from(getApplicationContext());
View view = layoutInflaterAndroid.inflate(R.layout.note_dialog, null);
AlertDialog.Builder alertDialogBuilderUserInput = new AlertDialog.Builder(CalendarEvent.this);
alertDialogBuilderUserInput.setView(view);
final EditText inputNote = view.findViewById(R.id.note);
TextView dialogTitle = view.findViewById(R.id.dialog_title);
dialogTitle.setText(!shouldUpdate ? getString(R.string.lbl_new_note_title) : getString(R.string.lbl_edit_note_title));
if (shouldUpdate && note != null) {
inputNote.setText(note.getNote());
}
alertDialogBuilderUserInput
.setCancelable(false)
.setPositiveButton(shouldUpdate ? "update" : "save", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogBox, int id) {
}
})
.setNegativeButton("cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogBox, int id) {
dialogBox.cancel();
}
});
final AlertDialog alertDialog = alertDialogBuilderUserInput.create();
alertDialog.show();
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Show toast message when no text is entered
if (TextUtils.isEmpty(inputNote.getText().toString())) {
Toast.makeText(CalendarEvent.this, "Enter note!", Toast.LENGTH_SHORT).show();
return;
} else {
alertDialog.dismiss();
}
// check if user updating note
if (shouldUpdate && note != null) {
// update note by it's id
updateNote(inputNote.getText().toString(), position);
} else {
// create new note
createNote(inputNote.getText().toString());
}
}
});
}
/**
* Toggling list and empty notes view
*/
private void toggleEmptyNotes() {
// you can check notesList.size() > 0
if (db.getNotesCount() > 0) {
noNotesView.setVisibility(View.GONE);
} else {
noNotesView.setVisibility(View.VISIBLE);
}
}
public String getDate(){
return date;
}
}
You are using wrong key while passing data between activity.
Replace below line,
intent.putExtra(Intent.EXTRA_TEXT,date);
With this one,
intent.putExtra(CalendarActivity.EXTRA_TEXT,date);
You use the key of Intent.EXTRA_TEXT.
intent.putExtra(Intent.EXTRA_TEXT,date)
But you use the other key to receive. It's not the same key.
intent.getStringExtra(CalendarActivity.EXTRA_TEXT);
As per I know (Not pretty sure)
Intent.EXTRA_TEXT
is used for implicit intents.
For explicit (i.e.Activity to Activity)
Do as below
Intent intent = new Intent(CalendarActivity.this,CalendarEvent.class);
intent.putExtra("DATE",date);
startActivity(intent);
To receive
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_notes);
intent = getIntent();
String date = intent.getStringExtra("DATE");
}
Where "DATE" is String KEY.
I would say that CalendarActivity.EXTRA_TEXT is probably empty because you have not imported that class in to CalendarEvent.java
import com.example.zaphk.studenthelperapplication3.calendar.CalendarActivity; in CalendarEvent.java
and as other people have said the put and get on the Intent need to be the the same String value.
On this page: https://developer.android.com/training/app-links/deep-linking, in the
'Read data from incoming intents'
section, Google mentions:
Once the system starts your activity through an intent filter, you can
use data provided by the Intent to determine what you need to render.
Call the getData() and getAction() methods to retrieve the data and
action associated with the incoming Intent.
And that's exactly what I'm trying to do, but, I'm unable to get help.
In this activity of mine:
package com.application;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
#SuppressWarnings("unused")
public class SplashActivity3 extends Activity
{
Handler Handler;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash3);
Handler = new Handler();
Handler.postDelayed(new Runnable()
{
#Override
public void run()
{
Intent intent = new Intent(SplashActivity3.this, MainActivity.class);
startActivity(intent);
finish();
}
},
1500);
Intent appLinkIntent = getIntent();
String appLinkAction = appLinkIntent.getAction();
Uri appLinkData = appLinkIntent.getData();
}
}
I want to know (later tranfer it to another activity), the URL that was clicked on to open my app.
Basically, my app is using App Links (referred to as Deep Linking by some). So, in a case where a user 'A', sends user 'B' a link of a page on my website and B has my app installed, he/she will be able to open the link in my app instead of the browser.
As of now, B can open the link in my app, but, my app will always load the 'home page' (it's because I have coded my app to open the home page by default). I want to load the page that brought B in my app.
For a real life example, just like Facebook's app does. Suppose I share a link of a Facebook page or a profile to my friend. It's a standard HTTP link that's displayed in my web browser. Probably, I shared it with him on WhatsApp. He touches the link to open it. He has the official Facebook app installed on his phone. So, Android asks him if he wants to open the link in the Facebook app or in the browser. Now, when he chooses the browser, it's no problem at all. But, when he chooses the Facebook app, the app loads the profile or the page that exists on the link and not the home page of Facebook. That's what I want to achieve.
Please note, I'm talking about standard HTTP links here and not my app specific URIs.
UPDATE:
Here's something I tried now:
This is the same activity as above, I modified it like this:
package com.application;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
#SuppressWarnings("unused")
public class SplashActivity3 extends Activity
{
Handler Handler;
#Override
protected void onCreate(Bundle savedInstanceState)
{
final Intent appLinkIntent = getIntent();
final String appLinkAction = appLinkIntent.getAction();
Uri appLinkData = appLinkIntent.getData();
final Bundle bundle = new Bundle();
bundle.putString("web", appLinkAction);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash3);
Handler = new Handler();
Handler.postDelayed(new Runnable()
{
#Override
public void run()
{
Intent intent = new Intent(SplashActivity3.this, WebViewActivity.class);
intent.putExtras(bundle);
startActivity(intent);
finish();
}
},
1500);
}
}
And the activity in which I'm loading the URL:
package com.application;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebChromeClient;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;
#SuppressWarnings("deprecation")
public class WebViewActivity extends AppCompatActivity
{
private WebView WebView;
private ProgressBar ProgressBar;
private LinearLayout LinearLayout;
private String currentURL;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState)
{
WebView wv = new WebView(this);
wv.loadUrl("file:///android_asset/eula.html");
wv.getSettings().setJavaScriptEnabled(true);
wv.getSettings().setUserAgentString("customUA");
wv.setWebViewClient(new WebViewClient()
{
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url3)
{
view.loadUrl(url3);
return true;
}
});
final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
boolean agreed = sharedPreferences.getBoolean("agreed",false);
if(!agreed)
{
new AlertDialog.Builder(this, R.style.AlertDialog)
.setIcon(R.drawable.ic_remove_circle_black_24dp)
.setTitle(R.string.eula_title)
.setView(wv)
.setCancelable(false)
.setPositiveButton(R.string.accept, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("agreed", true);
editor.apply();
}
})
.setNegativeButton(R.string.decline, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
finish();
}
})
.show();
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView = findViewById(R.id.webView5);
ProgressBar = findViewById(R.id.progressBar5);
LinearLayout = findViewById(R.id.layout5);
ProgressBar.setMax(100);
Bundle bundle = getIntent().getExtras();
String url = bundle.getString("web");
WebView.loadUrl(R.string.url);
WebView.getSettings().setJavaScriptEnabled(true);
WebView.getSettings().setUserAgentString("customUA");
WebView.setWebViewClient(new WebViewClient()
{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon)
{
LinearLayout.setVisibility(View.VISIBLE);
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url)
{
LinearLayout.setVisibility(View.GONE);
super.onPageFinished(view, url);
currentURL = url;
}
#Override
public void onReceivedError(WebView webview, int i, String s, String s1)
{
WebView.setVisibility(View.GONE);
Intent intent = new Intent(WebViewActivity.this, ErrorActivity.class);
startActivity(intent);
finish();
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url2)
{
if (url2.contains("www.mydomain.tld"))
{
view.loadUrl(url2);
return false;
} else
{
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url2));
startActivity(intent);
return true;
}
}
});
WebView.setWebChromeClient(new WebChromeClient()
{
#Override
public void onProgressChanged(WebView view, int newProgress)
{
super.onProgressChanged(view, newProgress);
ProgressBar.setProgress(newProgress);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
super.onPrepareOptionsMenu(menu);
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
#SuppressLint("SetJavaScriptEnabled")
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.backward:
onBackPressed();
break;
case R.id.forward:
onForwardPressed();
break;
case R.id.refresh:
WebView.reload();
break;
case R.id.share:
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT,currentURL);
startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.shareWith)));
break;
case R.id.update:
Intent intent = new Intent(WebViewActivity.this, UpdateActivity.class);
startActivity(intent);
finish();
break;
case R.id.about:
WebView wv2 = new WebView(this);
wv2.loadUrl("file:///android_asset/about.html");
wv2.getSettings().setJavaScriptEnabled(true);
wv2.getSettings().setUserAgentString("customUA");
wv2.setWebViewClient(new WebViewClient()
{
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url4)
{
view.loadUrl(url4);
return true;
}
});
new AlertDialog.Builder(this, R.style.AlertDialog)
.setIcon(R.drawable.ic_info_black_24dp)
.setTitle(R.string.info)
.setView(wv2)
.setPositiveButton(R.string.okay, null)
.show();
break;
case R.id.exit:
new AlertDialog.Builder(this,R.style.AlertDialog)
.setIcon(R.drawable.ic_error_black_24dp)
.setTitle(R.string.title)
.setMessage(R.string.message)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
finish();
}
})
.setNegativeButton(R.string.no, null)
.show();
break;
}
return super.onOptionsItemSelected(item);
}
private void onForwardPressed()
{
if (WebView.canGoForward())
{
WebView.goForward();
} else
{
Toast.makeText(this, R.string.noFurther, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onBackPressed ()
{
if (WebView.canGoBack())
{
WebView.goBack();
} else
{
new AlertDialog.Builder(this,R.style.AlertDialog)
.setIcon(R.drawable.ic_error_black_24dp)
.setTitle(R.string.title)
.setMessage(R.string.message)
.setPositiveButton(R.string.yes,
new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
finish();
}
})
.setNegativeButton(R.string.no, null)
.show();
}
}
}
But, I'm getting Cannot resolve symbol url error at WebView.loadUrl(R.string.url);
What to do?
I'm having an issue where I enter data into where my string keeps resetting to null even after I have entered data for it in my AlertDialog Fragment. What's supposed is that I enter data into a EditText object, store it in a string variable, set it as the string value in my Getter/Setter class then retrieve from that class in my fragment.
Image of AlertDialog
AlertDialog Fragment
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import org.ramferno.scoutapplication.ramfernoscout.R;
import org.ramferno.scoutapplication.ramfernoscout.providers.AddressProvider;
public class AddressDialogFragment extends DialogFragment {
AddressProvider addressProvider = new AddressProvider();
EditText enterIP;
String urlAddress;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
//Declare and initialize objects
LayoutInflater i = getActivity().getLayoutInflater();
View v = i.inflate(R.layout.fragment_dialog, null);
enterIP = (EditText) v.findViewById(R.id.enterIP);
//Create AlertDialog
AlertDialog.Builder b = new AlertDialog.Builder(getActivity())
.setTitle("Enter IP Address")
.setPositiveButton("ADD",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
urlAddress = enterIP.getText().toString();
addressProvider.setAddress(urlAddress);
} //End of onClick
}) //End of DialogInterface
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
} //End of onClick
} //End of DialogInterface
); //End of AlertDialog
b.setView(v);
return b.create();
} //End of onCreateDialog
} //End of class
Getter/Setter class
public class AddressProvider {
private String urlAddress;
public String getAddress() {
return urlAddress;
} //End of getAddress
public void setAddress(String urlAddress) {
this.urlAddress = urlAddress;
} //End of setAddress
} //End of class
ScoutFragment (Fragment that receives string from Getter/Setter)
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import org.ramferno.scoutapplication.ramfernoscout.downloaders.Downloader;
import org.ramferno.scoutapplication.ramfernoscout.R;
import org.ramferno.scoutapplication.ramfernoscout.providers.AddressProvider;
//Start of ScoutFragment
public class ScoutFragment extends Fragment {
//Declares Android UI objects
AddressProvider addressProvider = new AddressProvider();
FloatingActionButton addDataScout;
ListView eListScoutInfo;
String IP = addressProvider.getAddress();
//Declare and initialize variable
String urlAddress = "http://" + IP + "/ramfernoscout/matchdb/matchretrieve.php";
public ScoutFragment() {
// Required empty public constructor
} //End of ScoutFragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//Inflates layout for this fragment
View view = inflater.inflate(R.layout.fragment_scout, null, false);
//Instantiate ListView object with the xml ListView object
eListScoutInfo = (ListView) view.findViewById(R.id.listScoutInfo);
//Add instructions to the Refresh FAB that will download the data from the database server
FloatingActionButton fab = (FloatingActionButton) view.findViewById(R.id.fab2);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Downloader d = new Downloader(getActivity(),urlAddress,eListScoutInfo);
d.execute();
} //End of onClick
}); //End of setOnClickListener
//Change fragment to AddScoutDataFragment with animations
addDataScout = (FloatingActionButton) view.findViewById(R.id.fab);
addDataScout.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
AddScoutDataFragment fragment = new AddScoutDataFragment();
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.enter_from_right,
R.anim.exit_to_left, R.anim.enter_from_left, R.anim.exit_to_right);
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
} //End of onClick
}); //End of setOnClickListener
//Returns view
return view;
} //End of onCreateView
} //End of class
You are using AddressProvider addressProvider = new AddressProvider(); in both ScoutFragment and AddressDialogFragment.
The new operator will create a new instance of AddressProvider class. If you want to persist the data, you should create only a single instance of AddressProvider. So you should make AddressProvider a SingleTon class.
public class AddressProvider {
private static AddressProvider ourInstance = new AddressProvider();
private String urlAddress;
private AddressProvider() {
}
public static AddressProvider getInstance() {
return ourInstance;
}
public String getAddress() {
return urlAddress;
}
public void setAddress(String urlAddress) {
this.urlAddress = urlAddress;
}
}
Usage,
To store the IP,
AddressProvider.getInstance().setAddress("xxx.xxx.xx.xx");
to retrieve,
AddressProvider.getInstance().getAddress()
i have just started with android but have done some c# which seems very similar to java
in short, the problem lies in the closeDialog method
I am not very familiar with view/viewgroup so please dont bombard me with incorrect usage of objects, etc.
in short, i am creating a simple app which i hope to improve on (it is basically the start of a huge project)
the _showhint dialog opens fine, and shows the "hint" as expected, but the closeDialog force closes the app, I have no idea why
package com.example.app;
import android.app.Activity;
import android.app.Dialog;
import android.net.Uri;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.webkit.ValueCallback;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends ActionBarActivity {
private WebView webView;
final Activity activity = this;
public Uri imageUri;
private ValueCallback<Uri> mUploadMessage;
private Uri mCapturedImageImageURI = null;
private TextView lblAnswer, lblWelcome;
private EditText edtInput;
public TextView showText ;
public Button btnShowHint, btnCalculate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edtInput = (EditText) findViewById(R.id.edtInput) ;
lblWelcome = (TextView) findViewById(R.id.lblWelcome) ;
lblAnswer = (TextView) findViewById(R.id.lblAnswer) ;
btnShowHint = (Button) findViewById(R.id.btnHelp);
btnCalculate = (Button) findViewById(R.id.btnShow) ;
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
public void calculate(View vw)
{
String [] arrEditStore = new String[edtInput.length()] ;
String arrOperators [] = {"+", "-", "*", "/", "(", ")"} ;
}
public void _showhint(View vw)
{
final Dialog showHintDialog = new Dialog(activity);
showHintDialog.setContentView(R.layout.custom_dialog);
showHintDialog.setTitle("How to enter data");
showHintDialog.show();
}
public void closeDialog(View vw)
{
final Dialog dialog = new Dialog(this) ;
Button btnClose = (Button) dialog.findViewById(R.id.button) ;
btnClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
#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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
EDIT: ADDED "this" to final Dialog dialog = new Dialog(this)
I have discovered what has caused the problem
GIVEN CODE:
public void _showhint(View vw)
{
final Dialog showHintDialog = new Dialog(activity);
showHintDialog.setContentView(R.layout.custom_dialog);
showHintDialog.setTitle("How to enter data");
showHintDialog.show();
}
public void closeDialog(View vw)
{
final Dialog dialog = new Dialog(this) ;
Button btnClose = (Button) dialog.findViewById(R.id.button) ;
btnClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
SOULTION
first, I moved the decleration of the btnClose to the top
public Button btnShowHint, btnCalculate, btnClose;
then in the design view, removed the link of the button Close onclick method refering to closeDialog.
Afterwards, removing the closeDialog method completely, and also moving some of that code to the _showHint method
it also makes logical sense, thanks to #Mike M. who commented on the post, helped me reason it out, since I say, THIS button must close the dialog but in the method of this button, I am assigning it to be used by itself, which doesn't make logical sense at all, here is the changed code and it works
CHANGED CODE:
public void _showhint(View vw)
{
final Dialog showHintDialog = new Dialog(activity);
showHintDialog.setContentView(R.layout.custom_dialog);
showHintDialog.setTitle("How to enter data");
showHintDialog.show();
btnClose = (Button) showHintDialog.findViewById(R.id.button) ;
btnClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
showHintDialog.dismiss();
}
});
}
We all make stupid and unnessasary mistakes at times, some worse than others, but if you find a solution to a problem you have had, maybe somewhere someone has the same issue, so post a solution to your problem, it might help that someone!!!
cheers
I have Code Image with Pich zoom
package com.androidtutorialpoint;
import com.androidtutorialpoint.imageview.PhotoView;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
public class MainActivity extends Activity {
private ViewPager mViewPager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mViewPager = new HackyViewPager(this);
setContentView(mViewPager);
mViewPager.setAdapter(new SamplePagerAdapter());
}
static class SamplePagerAdapter extends PagerAdapter {
private static int[] sDrawables = {
R.drawable.ic_launcher,R.drawable.ic_launcher,
};
#Override
public int getCount() {
return sDrawables.length;
}
#Override
public View instantiateItem(ViewGroup container, int position) {
PhotoView photoView = new PhotoView(container.getContext());
photoView.setImageResource(sDrawables[position]);
// Now just add PhotoView to ViewPager and return it
container.addView(photoView, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
return photoView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}
}
I have add imageButton listner ale marker with function switching to a new activity
My Image button lister have Code
public class MainActivity extends Activity {
private ImageView mainBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainBtn = (ImageView) findViewById(R.id.button);
mainBtn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
openAlert(v);
}
});
}
private void openAlert(View view) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
alertDialogBuilder.setTitle(this.getTitle()+ " ");
// set positive button: Yes message
alertDialogBuilder.setPositiveButton("więcej",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// go to a new activity of the app
Intent positveActivity = new Intent(getApplicationContext(), PositiveActivity.class);
startActivity(positveActivity);
}
});
// set negative button: No message
alertDialogBuilder.setNegativeButton("wyjście",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// cancel the alert box and put a Toast to the user
dialog.cancel();
Toast.makeText(getApplicationContext(), "Mapa Budnik",
Toast.LENGTH_LONG).show();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
// show alert
alertDialog.show();
}
}
My Ask how to add a tag to the image Button and when you click the trigger Activity?
When my Image Button is in layaut.xml there is invisible.please help me