Android Studio - Passing variable with intent add extra, ends up with null - java

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.

Related

Getting one object less from the ROOM database

I am implementing a local database using ROOM in android studio. I am having a problem. I am successful in inserting and deleting the data entries into the database. But when I am getting all the data objects from the database then each time I am getting one object less.
When that activity starts then there is no problem but when I am trying to update the recycler view after inserting a new data object into the database then that object is being updated into the recycler view one step after creating a new data object entry and the same problem happens with this also.
below is my complete code:-
package com.example.eventus.DashBoard;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.DialogFragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Toast;
import com.example.eventus.ApplicationDatabase.Events.Event;
import com.example.eventus.ApplicationDatabase.Events.EventsAdapter;
import com.example.eventus.ApplicationDatabase.Events.EventsDao;
import com.example.eventus.R;
import com.example.eventus.Singletons.DatabaseSingleton;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
public class Dashboard extends AppCompatActivity implements View.OnClickListener, DatePickerDialog.OnDateSetListener {
//Declaring the views
private FloatingActionButton fbAddEvent;
private Button btnOKNewEvent, btnCancelNewEvent;
private EditText etDeadlineNewEvent, etTitleNewEvent, etInfoNewEvent;
//For recycler view
private RecyclerView rvEvents;
private RecyclerView.LayoutManager layoutManager;
private List<Event> events;
private EventsAdapter eventsAdapter;
//For alert box
private AlertDialog.Builder alertDialogBuilder;
private AlertDialog alertDialog;
private View alertDialogView;
//For database
private DatabaseSingleton databaseSingleton;
private EventsDao eventsDao;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
//Initializing and setting onclicklisteners on views
init();
//RecyclerView stuff
recyclerViewStuff();
//new event stuff
newEventDialog();
//database stuff
database();
//loadEvents
loadEvents();
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.fb_add_event_dashboard:
alertDialog.show();
}
}
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
Calendar mCalendar = Calendar.getInstance();
mCalendar.set(Calendar.YEAR, year);
mCalendar.set(Calendar.MONTH, month);
mCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
String selectedDate = DateFormat.getDateInstance(DateFormat.FULL).format(mCalendar.getTime());
etDeadlineNewEvent.setText(selectedDate);
}
private void init(){
//Initializing the views
rvEvents = findViewById(R.id.rv_events_dashboard);
fbAddEvent = findViewById(R.id.fb_add_event_dashboard);
//Setting onclicklisteners on views
fbAddEvent.setOnClickListener(this);
}
private void recyclerViewStuff() {
//Initializing the recycler view stuffs
layoutManager = new GridLayoutManager(this, 2);
rvEvents.setLayoutManager(layoutManager);
}
private void newEventDialog() {
alertDialogBuilder = new AlertDialog.Builder(Dashboard.this);
alertDialogView = getLayoutInflater().inflate(R.layout.new_event, null);
alertDialogBuilder.setView(alertDialogView);
alertDialog = alertDialogBuilder.create();
alertDialog.setCanceledOnTouchOutside(false);
//Instantiating the view
btnOKNewEvent = alertDialogView.findViewById(R.id.btn_ok_new_event);
etDeadlineNewEvent = alertDialogView.findViewById(R.id.et_deadline_new_event);
btnCancelNewEvent = alertDialogView.findViewById(R.id.btn_cancel_new_event);
etTitleNewEvent = alertDialogView.findViewById(R.id.et_title_new_event);
etInfoNewEvent = alertDialogView.findViewById(R.id.et_info_new_event);
//setting on click listeners for the views in dialog box
btnOKNewEvent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addEvent();
//loadEvents();
refreshEvents();
alertDialog.dismiss();
}
});
btnCancelNewEvent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialog.dismiss();
}
});
etDeadlineNewEvent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment datePicker = new com.example.eventus.DateAndTime.DatePicker();
datePicker.show(getSupportFragmentManager(), null);
}
});
}
private void database(){
//getting the database instance
databaseSingleton = DatabaseSingleton.getInstance();
//getting the events dao
eventsDao = databaseSingleton.getEventsDao(getApplicationContext());
//deleting all previously saved events
eventsDao.deleteAllEvent();
}
private void addEvent() {
String eventTitle, eventInfo, eventDeadline;
eventTitle = etTitleNewEvent.getText().toString();
eventInfo = etInfoNewEvent.getText().toString();
eventDeadline = etDeadlineNewEvent.getText().toString();
//creating an event
Event event = new Event(eventTitle, eventInfo, eventDeadline);
Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
eventsDao.createEvent(event);
Toast.makeText(Dashboard.this, "Event Created", Toast.LENGTH_SHORT).show();
}
};
handler.post(runnable);
}
private void loadEvents(){
events = eventsDao.getEvents();
eventsAdapter = new EventsAdapter(events);
rvEvents.setAdapter(eventsAdapter);
}
private void refreshEvents(){
events.clear();
List<Event> tempEventsList = eventsDao.getEvents();
for(int i=0;i<tempEventsList.size();i++){
events.add(tempEventsList.get(i));
}
eventsAdapter.notifyDataSetChanged();
}
}
The problem you are having is realted to concurrency. If you check your code you first call the add event method and place the insertion inside a Runnable, this tells the application to execute at a later time when possible, but it does not execute it inmediately; therefor the code continues its execution, you fetch the events and then, at a later time, the new event is added.
To solve your problem, try to place the call of the method refreshEvents inside the runnable.
Runnable runnable = new Runnable() {
#Override
public void run() {
eventsDao.createEvent(event);
Toast.makeText(Dashboard.this, "Event Created", Toast.LENGTH_SHORT).show();
refreshEvents();
}
};
handler.post(runnable);
EDIT: As correctly said in the comments is not a mult-thread issue, it's the execution time of code fragments inside a single thread.

Can't access ArrayAdapter from AlertDialog

TL;DR
I don't understand how to change my ArrayList dataset from a dialog so that it updates my listview. My current solution crashes because the ListView doesn't update. Need to know where my code is going wrong.
The Problem
I have one activity that has a ListView of items with an ArrayAdapter that connects it to my data (ArrayList). When a user clicks on an item in that list I load an AlertDialog that allows the user to delete that item. Debugging shows that the item does get removed from the data, the dialog closes as expected but the ListView doesn't update and subsequent clicks cause the app to crash.
The problem seems to be tied to the itemsList.notifyDataSetChanged();. I've tried hitting the adapter instead but then the Adapter itself can't be resolved.
I know this is due to an error on my part but I can't find where I'm going wrong.
The Code
ScannerActivity.java
import android.content.Intent;
import android.graphics.pdf.PdfDocument;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
public class ScannerActivity extends AppCompatActivity {
Button delete, deleteAll, manual, export, newPull;
EditText input_main;
static int pulls = 001;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scanner);
//Load some items for testing
final PullSheet pullSheet = new PullSheet();
pullSheet.createSheet(nameText, roleText, storeText, runitText);
pullSheet.addItem("12543", 5);
pullSheet.addItem("3526", 1);
pullSheet.addItem("00045", 3);
pullSheet.addItem("95462", 18);
pullSheet.addItem("1181", 53);
pullSheet.addItem("6543", 1);
final ArrayAdapter<PullItem> itemAdapter =
new ArrayAdapter<PullItem>(this, 0, pullSheet.SheetItems) {
#Override
public View getView(int position,
View convertView,
ViewGroup parent){
PullItem currentItem = getItem(position);//
if(convertView == null) {
convertView = getLayoutInflater()
.inflate(R.layout.item, null, false);
}
TextView itemSku =
(TextView)convertView.findViewById(R.id.item_sku);
TextView itemQty =
(TextView)convertView.findViewById(R.id.item_qty);
itemSku.setText(currentItem.sku);
itemQty.setText(String.valueOf(currentItem.qty));
return convertView;
}
};
final ListView itemsList = (ListView) findViewById(R.id.itemsList);
itemsList.setAdapter(itemAdapter);
itemsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(final AdapterView<?> itemAdapter,
View view, int position, long rowId) {
final PullItem item = pullSheet.SheetItems.get(position);
final PullSheet sheet = pullSheet;
//load dialog
final AlertDialog.Builder mBuilder = new AlertDialog.Builder(ScannerActivity.this);
final View mView = getLayoutInflater().inflate(R.layout.dialog_interact, null);
//Declare dialog ui elements
Button mYes = (Button) mView.findViewById(R.id.btnYes);
Button mNo = (Button) mView.findViewById(R.id.btnNo);
TextView skuData = (TextView) mView.findViewById(R.id.skuData);
TextView qtyData = (TextView) mView.findViewById(R.id.qtyData);
skuData.setText(item.sku);
qtyData.setText(item.qty.toString());
mBuilder.setView(mView);
final AlertDialog dialog = mBuilder.create();
dialog.show();
mYes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deletePullItem(sheet, item);
itemsList.notifyDataSetChanged();// This isn't working, "Cannot resolve method notifyDataSetChanged()"
dialog.dismiss();
}
});
mNo.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
});
}
public void deletePullItem(PullSheet sheet, PullItem item)
{
sheet.removeItem(item);
}
}
PullSheet.java
import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.UUID;
public class PullSheet extends Application{
protected String pullerName;
protected String role;
protected String store;
protected String sheetId;
protected String runItId;
protected Long startTime = System.currentTimeMillis();
protected ArrayList<PullItem> SheetItems = new ArrayList<PullItem>();
public void createSheet(String _pullerName, String _role, String _store, String _runItId){
setPullerName(_pullerName);
setRole(_role);
setStore(_store);
setRunItId(_runItId);
setSheetId();
}
protected void addItem(String sku, Integer qty){
SheetItems.add(new PullItem(sku, qty));
}
protected void removeItem(PullItem item){
this.SheetItems.remove(item);
}
//Getters and setters
public String getPullerName(){ return pullerName; }
public String getRole(){
return role;
}
public String getStore(){
return store;
}
public String getRunItId(){
return runItId;
}
public String getSheetId(){
return sheetId;
}
public Long getStartTime(){
return startTime;
}
private void setPullerName(String _pullerName){ pullerName = _pullerName; }
private void setRole(String _role){ pullerName = _role; }
private void setStore(String _store){ store = _store; }
private void setRunItId(String _runItId){ runItId = _runItId; }
private void setSheetId(){
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
String dateString = formatter.format(new Date(startTime));
UUID uuid = UUID.randomUUID();
String randUUID = uuid.toString();
sheetId = dateString + "-" + this.pullerName + "-" + randUUID + "-" + runItId;
}
}
PullItem.java
public class PullItem {
protected String sku;
protected Integer qty;
public PullItem(String sku, Integer qty) {
setSku(sku);
this.qty = 1;
}
String getSku(){ return sku; }
Integer getQty(){ return qty; }
void setSku(String _sku){ sku = _sku; }
void setQty(Integer _qty){ qty = _qty; }
void incrementQty(){ qty += 1; }
}
The Solution
I need to be told where I'm going wrong. I know it has to do with the ArrayAdapter and the ListView, but Everything I've tried just moves the "Can't resolve" to another part of the expression.
Thanks in advance for any help
notifyDatasetChanged() is an Adapter method, so you can't use it with ListView
But this should work:
Make your Adapter a member variable (instantiate it the way you did) so you can access it everywhere in the Activity:
private ArrayAdapter<PullItem> itemAdapter;
Simply call deletePullItem() if the user clicks the OK-Button:
mYes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deletePullItem(sheet, item);
dialog.dismiss();
}
});
And call notifyDatasetChanged() when really deleting the item:
public void deletePullItem(PullSheet sheet, PullItem item)
{
sheet.removeItem(item);
itemAdapter.notifyDatasetChanged();
}
Try this:
mYes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deletePullItem(sheet, item);
itemsList.getAdapter().notifyDataSetChanged();
dialog.dismiss();
}
});

How to pass date from one fragment to another in the same activity in Android?

I am having trouble passing the data (the user selected date from the Date Widget) from the widget back to the calling fragment and set it on the Button. The starting fragment successfully passes the current date to the widget but having troubles passing the user selected date back to the calling fragment.
Here is the code for Starting fragment i.e. CrimeFragment
package com.khalsa.gurankassingh.criminalintent;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import java.util.Date;
import java.util.UUID;
/**
* Created by Gurankas Singh on 3/12/2017.
*/
public class CrimeFragment extends Fragment
{
public static final String ARG_CRIME_ID = "crime_id";
public static final String DIALOG_DATE = "DialogDate";
private static final int REQUEST_DATE = 0;
private Crime mCrime; //instance of the Crime class
private EditText mTitleField; // The editable text field in the fragment
private Button mDateButton; //Displays the date of the crime on the button
private CheckBox mSolvedCheckBox; //Displays the current status of the crime; solved or unsolved
public static CrimeFragment newInstance(UUID crimeID) //to pass value to the fragment via an argument to another fragment
{
Bundle args = new Bundle();
args.putSerializable(ARG_CRIME_ID,crimeID);
CrimeFragment fragment = new CrimeFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
UUID crimeId = (UUID)getArguments().getSerializable(ARG_CRIME_ID);
mCrime = CrimeLab.get(getActivity()).getCrime(crimeId);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.fragment_crime,container,false);
mTitleField = (EditText) v.findViewById(R.id.crime_title);
mTitleField.setText(mCrime.getTitle());
mTitleField.addTextChangedListener(new TextWatcher()
{
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
mCrime.setTitle(s.toString());
}
#Override
public void afterTextChanged(Editable s)
{
}
});
mDateButton = (Button) v.findViewById(R.id.crime_date);
updateDate();
mDateButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
FragmentManager fragmentManager = getFragmentManager();
DatePickerFragment dialog = DatePickerFragment.newInstance(mCrime.getDate());
setTargetFragment(CrimeFragment.this,REQUEST_DATE);
dialog.show(fragmentManager, DIALOG_DATE);
}
});
mSolvedCheckBox = (CheckBox) v.findViewById(R.id.crime_solved);
mSolvedCheckBox.setChecked(mCrime.isSolved());
mSolvedCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
//set the crime's solved property
mCrime.setSolved(isChecked);
}
});
return v;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode != Activity.RESULT_OK)
{
return;
}
if (requestCode == REQUEST_DATE)
{
Date date = (Date)data.getSerializableExtra(DatePickerFragment.EXTRA_DATE);
mCrime.setDate(date);
updateDate();
}
}
private void updateDate()
{
mDateButton.setText(DateFormat.format("EEEE, d MMMM, yyy", mCrime.getDate()));
}
}
Here is the code for the datePicker widget hosted by DatePickerFragment
package com.khalsa.gurankassingh.criminalintent;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.DatePicker;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
/**
* Created by Gurankas Singh on 4/9/2017.
*/
public class DatePickerFragment extends DialogFragment
{
private static final String DATE_ARG = "date";
public static final String EXTRA_DATE = "com.khalsa.gurankassingh.criminalintent.date";
private DatePicker mDatePicker;
public static DatePickerFragment newInstance(Date date)
{
Bundle args = new Bundle();
args.putSerializable(DATE_ARG,date);
DatePickerFragment fragment = new DatePickerFragment();
fragment.setArguments(args);
return fragment;
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
Date date = (Date)getArguments().getSerializable(DATE_ARG);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
View v = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_date,null);
mDatePicker = (DatePicker)v.findViewById(R.id.dialog_date_date_picker);
mDatePicker.init(year,month,day,null);
return new AlertDialog.Builder(getActivity()).setView(v).setTitle(R.string.date_picker_title).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
int year = mDatePicker.getYear();
int month = mDatePicker.getMonth();
int day = mDatePicker.getDayOfMonth();
Date date = new GregorianCalendar(year, month, day).getTime();
sendResult(Activity.RESULT_OK, date);
}
}).create();
}
private void sendResult(int resultCode, Date date)
{
if (getTargetFragment() == null)
{
return;
}
Intent intent = new Intent();
intent.putExtra(EXTRA_DATE,date);
getTargetFragment().onActivityResult(getTargetRequestCode(), resultCode, intent);
}
}
For passing data between Fragments all you need to know is:
1- For passing data from Activity to Fragment use object instance, as you create your Fragment inside Activity you have one instance from it, so use that to pass data like below:
class Activity1 extend AppCompatActivity {
Fragment1 fragment;
void doSomethingInFramgent() {
fragment.doSomething();
}
}
2- for passing data from Fragment to Activity, use Interface, create an Interface and use following step:
2-1- create an Interface file:
public interface FragmentInteraction {
void doSomethingInActivity();
}
2-2- implement Interface in Activity:
class Activity1 extend AppCompatActivity implement FragmentInteraction {
void doSomethingInActivity() {
// do whatever you need
}
}
2-3- create one object from Interface and initialize it in onAttach like bellow:
class Fragment1 extend Fragment {
FragmentInteraction fragmentInteraction;
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof FragmentInteraction) {
fragmentInteraction = (FragmentInteraction) context;
}
}
}
2-4- use Interfaceinstance to call method in Activity like:
fragmentInteraction.doSomethinInActivity();
with this concept you can pass data between Fragments and Activity, for example if you want pass data from one fragment to another in different activity you can:
Activity1, Fragment1. Activity2, Fragment2
pass data with Interface from Fragment1 to Activity1, start Activity2 with startActivityForResult, pass data with fragment2 object, return data with Interface to Activity2 then use setResult and return to Activity1
PS: if you want pass data while creation Fragment object you can use Argument to pass data.
for this purpose you can use as follow:
1- create static method for get instance of fragment:
public static Fragment1 getInstance(String data1) {
Fragment1 fragment = new Fragment1();
Bundle bundle = new Bundle();
bundle.putString(KEY, data1);
fragment.setArguments(bundle);
return fragment;
}
then in onCreateView on onViewCreate get your data like:
if (getArguments() != null) {
data = getArguments().getString(KEY);
}
You can try this solution:-
=> Change below code in CrimeFragment
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode != Activity.RESULT_OK)
{
return;
}
if (requestCode == REQUEST_DATE)
{
long dateValue = data.getLongExtra(DatePickerFragment.EXTRA_DATE,System.currentTimeMillis());
Date date = new Date(dateValue);
mCrime.setDate(date);
updateDate();
}
}
And In DatePickerFragment change below code:-
private void sendResult(int resultCode, Date date)
{
if (getTargetFragment() == null)
{
return;
}
Intent intent = new Intent();
intent.putExtra(EXTRA_DATE, date.getTime());
getTargetFragment().onActivityResult(getTargetRequestCode(), resultCode, intent);
}
....
Hello Try this approach,
You can use shared preferences to store the date and later on you can access it whenever required, it is easier to handle.just keep in mind the date format and choose the SimpleDateFormat accordingly as it gives parse error if a format of input date is not same.
Write into SharedPreferances
SharedPreferences sharedpreferences;
sharedpreferences = getSharedPreferences("myPref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("Date",String.valueOf(date);
editor.commit();
Read SharedPreferances when required
SharedPreferences prefs = this.getSharedPreferences("myPref", Context.MODE_PRIVATE);
String dateCrime = prefs.getString("Date", null);
//Chose Date format depending on your date
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
try {
Date date = format.parse(dateCrime);
} catch (ParseException e) {
e.printStackTrace();
}

Handling orientation change in android studio

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.

Webview is blank or loading same page for different urls

A search api is returning me some meta data i.e a url "eventURL" and trackbackurl i.e "trackBack". I am placing the data in the listview, each row containing some data and a unique url and trackback url.When user taps on the row in the listview, a alert dialog is displayed presenting user 2 options. Clicking on option 1 should launch trackback url in a webview while clicking on second opion should launch eventURL in a webview.I have created a WebViewActivity for it,Problem is that my webview is always blank.
Main Activity
package my.stayactive.plan;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import my.stayactive.plan.ActiveHelper.ApiException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class StayActiveActivity extends Activity implements OnItemClickListener {
//private EditText m_search_text;
protected EditText m_zip;
private ListView m_search_results;
private Button m_search_btn;
private JSONArray m_results;
private LayoutInflater m_inflater;
private InputMethodManager m_ctrl;
private Spinner m_radius;
private Spinner m_activity_selector;
public static int radius = 0;
public static String activities;
public String url;
public String trackBack;
public static String assetId;
static final private int EXIT_ID = Menu.FIRST;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// m_search_text = (EditText) findViewById(R.id.search_text);
m_zip = (EditText) findViewById(R.id.zip);
m_search_btn = (Button) findViewById(R.id.search_button);
// m_searchm_results = (ListView) findViewById(R.id.lview);
m_search_btn .setOnClickListener(go_handler);
m_ctrl = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
m_inflater = LayoutInflater.from(this);
addListenerOnSpinnerItemSelection();
addListenerOnSpinner1ItemSelection();
m_search_results = (ListView)findViewById(R.id.lview);
m_search_results.setOnItemClickListener(this);
}
public void addListenerOnSpinnerItemSelection() {
m_radius = (Spinner) findViewById(R.id.spinner);
m_radius.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}
public void addListenerOnSpinner1ItemSelection(){
m_activity_selector = (Spinner) findViewById(R.id.spinner1);
m_activity_selector.setOnItemSelectedListener(new ActivitySelectedListener());
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
super.onCreateOptionsMenu(menu);
menu.add(0, EXIT_ID, 0, R.string.exit);
return true;
}
#Override
public boolean onOptionsItemSelected (MenuItem item){
switch (item.getItemId()){
case EXIT_ID:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
OnClickListener go_handler = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//m_ctrl.hideSoftInputFromWindow(m_search_text.getWindowToken(), 0);
m_ctrl.hideSoftInputFromWindow(m_zip.getWindowToken(), 0);
//String searchText = Uri.encode(m_search_text.getText().toString());
String zip = Uri.encode(m_zip.getText().toString());
new SearchTask().execute("?k=Fall+Classic" + "&m=meta:channel=" + activities + "&l="+ zip + "&r=" + radius);
// Show a toast showing the search text
Toast.makeText(getApplicationContext(),
getString(R.string.search_msg) + " " +
activities, Toast.LENGTH_LONG).show();
}
};
private class SearchTask extends AsyncTask<String, Integer, String>
{
ProgressDialog dialog;
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(StayActiveActivity.this,"","Please Wait...");
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
String result = ActiveHelper.download(params [0]);
return result;
} catch (ApiException e) {
e.printStackTrace();
Log.e("alatta", "Problem making search request");
}
return "";
}
#Override
protected void onPostExecute(String result) {
dialog.hide();
try {
JSONObject obj = new JSONObject(result);
m_results = obj.getJSONArray("_results");
if (m_results == null || m_results.length() == 0)
{
Toast.makeText(getApplicationContext(),
"No Results found for " + activities,
Toast.LENGTH_LONG).show();
}
else
m_search_results.setAdapter(new JSONAdapter(getApplicationContext()));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private class JSONAdapter extends BaseAdapter
{
public JSONAdapter(Context c){
}
public int getCount()
{
return m_results.length();
}
public Object getItem(int arg0){
return null;
}
public long getItemId(int pos){
return pos;
}
public View getView(int pos, View convertView, ViewGroup parent) {
View tv;
TextView t;
if (convertView == null)
tv = m_inflater.inflate (R.layout.item, parent, false);
else
tv = convertView;
try {
/* For each entry in the ListView, we need to populate
* its text and timestamp */
t = (TextView) tv.findViewById(R.id.text);
JSONObject obj = m_results.getJSONObject(pos);
t.setText (obj.getString("title").replaceAll("</?(?i:<|>|...|&quot|&amp|;|)(.|\n)*?>", ""));
//("\\<.*?\\>", ""))
t = (TextView) tv.findViewById(R.id.created_at);
JSONObject meta = obj.getJSONObject("meta");
// url = meta.getString("eventURL");
trackBack = obj.getString("url");
assetId = meta.getString("assetTypeId");
//String eventDate = meta.getString("startDate");
Calendar currentDate = Calendar.getInstance();
long dateNow = currentDate.getTimeInMillis();
String eventDate = meta.getString("startDate");
String endDate = meta.getString("endDate");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
Date date2 = null;
try {
date = formatter.parse(eventDate);
date2 = formatter.parse(endDate);
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long modifiedDate= date.getTime();
long modifiedEndDate = date2.getTime();
if ( Long.valueOf(dateNow).compareTo(Long.valueOf(modifiedDate)) > 0 || Long.valueOf(dateNow).compareTo(Long.valueOf(modifiedEndDate)) > 0)
{
t.setText ("Was:" + "\t"+eventDate+"\n"+"Location:" +"\t" +meta.getString("location")+"\n" + meta.getString("eventURL") +"\n"+ obj.getString("url"));
}
else {
t.setText ("When:" + "\t"+eventDate+"\n"+"Location:" +"\t" +meta.getString("location")+"\n"+ meta.getString("eventURL") +"\n"+ obj.getString("url"));
}
} catch (JSONException e) {
Log.e("alatta", e.getMessage());
}
return tv;
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
/*try {
JSONObject obj = m_results.getJSONObject(position);
JSONObject meta = obj.getJSONObject("meta");
url = meta.getString("eventURL");
//Intent intent = new Intent (StayActiveActivity.this, WebViewActivity.class);
//StayActiveActivity.this.startActivity(intent);
} catch (JSONException e) {
Log.e("alatta",e.getMessage());
}*/
// TODO Auto-generated method stub
final CharSequence[] items = {"Register", "Additional Information"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Please Select an Option");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
if (which == 0){
Intent intent1 = new Intent (StayActiveActivity.this, ReviewActivity.class);
StayActiveActivity.this.startActivity(intent1);
}
else if ( which == 1){
Intent intent = new Intent (StayActiveActivity.this, WebViewActivity.class);
StayActiveActivity.this.startActivity(intent);
}
}
});
AlertDialog alert = builder.create();
alert.show();
}}
WebViewActivity
package my.stayactive.plan;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class WebViewActivity extends StayActiveActivity {
private WebView webView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
webView = (WebView) findViewById(R.id.webView);
WebSettings setting = webView.getSettings();
setting.setJavaScriptEnabled(true);
if (url != null && url.length()>0) {
webView.loadUrl(url);
}
}
}
You didn't pass URL to your WebViewActivity. To do that:
Before calling startActivity(), attach your URL to the intent with setData().
In onCreate() of WebViewActivity, retrieve the URL with getData(), then load it.
Or search for putExtra(...). You can transfer a number of data with Intent.
— edited —
Example:
To set data:
import android.net.Uri;
//...
Intent intent = new Intent (StayActiveActivity.this, WebViewActivity.class);
intent.setData(Uri.parse("your-url"));
StayActiveActivity.this.startActivity(intent);
To retrieve data:
//...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//...
Uri uri = getIntent().getData();
//...
webView.loadUrl(uri.toString());
}
My guess is that your URLs are redirecting and that you aren't handling the redirects so nothing is being shown.
try adding this to your webview activity:
mWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return false;
}
});
Also it would be a good idea since you have an if statement in your WebView activity to log the url so that you can be certain that it is actually making it in to the activity correctly. If not the web view would never load anything.
EDIT: actually upon closer look it doesn't seem like you're setting the 'url' variable anywhere so it would be null, thus not calling your loadUrl method because of the if statement.

Categories

Resources