App crashing when attempting to add to ArrayAdapter - java

I am working on an assignment for school, the instructions are to create a Bookmark app with two activities, one named BookNote which must be a List Activity and another called ManageActivity.
BookNote is to populate the List Activity on startup with data read from a file, if no file is present an example bookmark is created. Bookmarks can be added, edited, and deleted, but all typing must be done in ManageActivity. Whenever Booknote handles the data returned from ManageActivity it should alter the list.
The code I have now has comments showing my intentions for each function, but my current problem is that everytime I return to BookNote from ManageActivity, the app crashes with the error "Attempt to invoke virtual method 'void android.widget.ArrayAdapter.insert(java.lang.Object, int)' on a null object reference" when attempting to add or insert a new bookmark object into the ArrayAdapter.
BookNote Activity
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class BookNote extends ListActivity{
private ArrayAdapter<Bookmark> adapter;
private final String FILENAME = "bookmarks.txt";
public String title = "EMPTY", url = "EMPTY", note = "EMPTY";
public String bookmarkClicked ="";
public int listViewID = 0;
public boolean intentListener = false;
public boolean addBookmarkClicked = false;
/*When activity is called, list is populated by readData(), addBookmarkClicked is reset to false, intentLister is changed to true if returning from ManageActivity,
if intentListener is true, addBookmarkClicked will be changed to true if AddBookmark is clicked from the BookNote menubar, a bookmark object will be created with information
passed back from ManageActivity, and if addBookmarkClicked is true, the bookmark object will be added to the end of the list, otherwise it will be inserted in the same
list element from which was chosen to edit.*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayList<Bookmark> bookmarkList = readData();
ArrayAdapter adapter = new ArrayAdapter<Bookmark>(this, android.R.layout.simple_list_item_1, bookmarkList);
setListAdapter(adapter);
addBookmarkClicked = false;
intentListener = false;
intentListener = getIntent().getBooleanExtra("listen", false);
if(intentListener == true) {
addBookmarkClicked = getIntent().getBooleanExtra("addClicked", false);
title = getIntent().getExtras().getString("title");
url = getIntent().getExtras().getString("url");
note = getIntent().getExtras().getString("note");
listViewID = getIntent().getExtras().getInt("listViewID");
Bookmark bookmark = new Bookmark(title,url,note);
Toast.makeText(getApplicationContext(), "Intent return: True", Toast.LENGTH_SHORT).show();
if(addBookmarkClicked == true) {
addBookmark(bookmark);
}
else {
insertBookmark(bookmark, listViewID);
}
//writeData();
}
}
//When list item is clicked, fill bookmarkClicked with values in list item, record item position, and call gotoManageActivity() to pass information to ManageActivity.
public void onListItemClick(ListView listView, View view, int position, long id) {
ListView myListView = getListView();
Object itemClicked = myListView.getAdapter().getItem(position);
Toast.makeText(getApplicationContext(), "Item clicked: " + itemClicked + "\nItem ID: " + id,Toast.LENGTH_SHORT).show();
bookmarkClicked = itemClicked.toString();
listViewID = position;
gotoManageActivity();
}
//reads data when app runs and fills arrayadapter and list with items saved to bookmarks.txt
private ArrayList<Bookmark> readData(){
ArrayList<Bookmark> bookmarks = new ArrayList<>();
try {
FileInputStream fis = openFileInput(FILENAME);
Scanner scanner = new Scanner(fis);
if (scanner.hasNext()){
String titleScan = scanner.nextLine();
String urlScan = scanner.nextLine();
String noteScan = scanner.nextLine();
Bookmark bookmark = new Bookmark(titleScan, urlScan, noteScan);
bookmarks.add(bookmark);
}else{
Bookmark bookmark = new Bookmark("Example Title", "Example URL", "Example Note");
bookmarks.add(bookmark);
}
scanner.close();
} catch (FileNotFoundException e) {
}
return bookmarks;
}
//If addBookmark menu item is clicked, this will be called to add a bookmark to the end of the ArrayAdapter.
private void addBookmark(Bookmark bookmark){
adapter.add(bookmark);
//writeData();
}
//If a list item is clicked, any edits will be inserted back into the ArrayAdapter in the same position of the item clicked.
private void insertBookmark(Bookmark bookmark, int listViewID){
adapter.insert(bookmark,listViewID);
//writeData();
}
//Calls ManageActivity and reports information about app.
public void gotoManageActivity(){
Intent manageIntent = new Intent(this, ManageActivity.class);
Bundle extras = new Bundle();
extras.putString("bookmark", bookmarkClicked);
extras.putBoolean("addBookmarkClicked", addBookmarkClicked);
extras.putInt("listViewID", listViewID);
manageIntent.putExtras(extras);
startActivity(manageIntent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_book_note, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_add) {
addBookmarkClicked = true;
gotoManageActivity();
return true;
}
return super.onOptionsItemSelected(item);
}
}
ManageActivity
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.InputType;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class ManageActivity extends AppCompatActivity {
private String title = "EMPTY", url = "EMPTY", note = "EMPTY";
private boolean listener = true;
private boolean addBookmarkClicked = false;
/* When activity starts, check for addBookmarkClicked status, create book */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.manage_layout);
addBookmarkClicked = getIntent().getBooleanExtra("addClicked", false);
String bookmarkString = "";
bookmarkString = getIntent().getExtras().getString("bookmark");
if(bookmarkString != null && bookmarkString.length() > 0) {
if (bookmarkString.length() != 0) {
String[] stringArray = bookmarkString.split("\\n");
title = stringArray[0];
url = stringArray[1];
note = stringArray[2];
updateTextViews();
}
}
else {
updateTextViews();
}
}
#Override
public void onBackPressed(){
Intent bookNoteIntent = new Intent(this, BookNote.class);
startActivity(bookNoteIntent);
Bundle extras = new Bundle();
extras.putString("title", title);
extras.putString("url", url);
extras.putString("note", note);
extras.putBoolean("listen", listener);
extras.putBoolean("addBookmarkClicked", addBookmarkClicked);
bookNoteIntent.putExtras(extras);
startActivity(bookNoteIntent);
}
public void editButtonCall(View view){
showNoteDialog();
showURLDialog();
showTitleDialog();
}
public void webButton(View view){
if(url.length() != 0 && url != "EMPTY"){
}
}
public void updateTextViews(){
TextView titleTextView = (TextView) findViewById(R.id.titleTV);
TextView urlTextView = (TextView) findViewById(R.id.urlTV);
TextView noteTextView = (TextView) findViewById(R.id.noteTV);
titleTextView.setText("Title: " + title);
urlTextView.setText("URL: " + url);
noteTextView.setText("Note: " + note);
}
//Show dialog and editText for user to assign title to bookmark.
public void showTitleDialog(){
AlertDialog.Builder titleBuilder = new AlertDialog.Builder(this);
titleBuilder.setTitle("Enter Title");
final EditText titleET = new EditText(this);
titleET.setInputType(InputType.TYPE_TEXT_VARIATION_NORMAL);
titleBuilder.setView(titleET);
titleBuilder.setPositiveButton("Add", newDialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
title = titleET.getText().toString();
updateTextViews();
}
});
titleBuilder.show();
}
//Show dialog and editText for user to assign note to bookmark.
public void showNoteDialog(){
AlertDialog.Builder noteBuilder = new AlertDialog.Builder(this);
noteBuilder.setTitle("Enter Note");
final EditText noteET = new EditText(this);
noteET.setInputType(InputType.TYPE_TEXT_VARIATION_NORMAL);
noteBuilder.setView(noteET);
noteBuilder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
note = noteET.getText().toString();
updateTextViews();
}
});
noteBuilder.show();
}
//Show dialog and editText for user to assign url to bookmark.
public void showURLDialog(){
AlertDialog.Builder urlBuilder = new AlertDialog.Builder(this);
urlBuilder.setTitle("Enter URL");
final EditText urlET = new EditText(this);
urlET.setInputType(InputType.TYPE_TEXT_VARIATION_NORMAL);
urlBuilder.setView(urlET);
urlBuilder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
url = urlET.getText().toString();
updateTextViews();
}
});
urlBuilder.show();
}
}

You are declaring a global and a local instance of adapter. In onCreate() method of BookNote Activity, remove the local instance. Change
ArrayAdapter adapter = new ArrayAdapter<Bookmark>(this, android.R.layout.simple_list_item_1, bookmarkList);
to
adapter = new ArrayAdapter<Bookmark>(this, android.R.layout.simple_list_item_1, bookmarkList);

You are not setting xml file which contains
book_layout.xml
<ListView android:id="#+id/android:list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.book_layout);
ArrayList<Bookmark> bookmarkList = readData();
ArrayAdapter adapter = new ArrayAdapter<Bookmark>(this, android.R.layout.simple_list_item_1, bookmarkList);
setListAdapter(adapter);

Related

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

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.

I'm using List View Activity to send data to Edit Data Activity, what's the problem here?

I m retrieving item name, item description and item price from database, when user clicks on item, it will take to the edit activity where user can update or delete data, But When i click on List Item it takes me back to the Main Activity
When user clicks on view data, it displays list view
after clicking list view user should move to edit data activity, where in edit data activity data will display in edit texts boxes for update or delete
my code was running fine with one parameter item name, but when i used item description, and item price, there's this error
private static final String TAG = "ListDataActivity";
DatabaseHelper mDatabaseHelper;
private ListView mListView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_data);
mListView = (ListView) findViewById(R.id.listView);
mDatabaseHelper = new DatabaseHelper(this);
populateListView();
}
private void populateListView() {
Log.d(TAG, "populateListView: Displaying data in the ListView.");
Cursor data = mDatabaseHelper.getData();
ArrayList<String> listData = new ArrayList<>();
while(data.moveToNext()){
listData.add(data.getString(1));
}
ListAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listData);
mListView.setAdapter(adapter);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String name = adapterView.getItemAtPosition(i).toString();
String des = adapterView.getItemAtPosition(i).toString();
String pri = adapterView.getItemAtPosition(i).toString();
Log.d(TAG, "onItemClick: You Clicked on " + name);
Cursor data = mDatabaseHelper.getItemID(name, des, pri); //get the id associated with that name
int itemID = -1;
while(data.moveToNext()){
itemID = data.getInt(0);
}
if(itemID > -1){
Log.d(TAG, "onItemClick: The ID is: " + itemID);
Intent intent = new Intent(ListDataActivity.this, EditDataActivity.class);
Bundle extras = new Bundle();
extras.putInt("id",itemID);
extras.putString("name",name);
extras.putString("description",des);
extras.putString("price",pri);
intent.putExtras(extras);
startActivity(intent);
}
else{
toastMessage("No ID associated with that name");
}
}
});
}
private void toastMessage(String message){
Toast.makeText(this,message, Toast.LENGTH_SHORT).show();
}
new updated code, i have made the following changes
package com.example.saveanddisplaysql;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class ListDataActivity extends AppCompatActivity {
private static final String TAG = "ListDataActivity";
DatabaseHelper mDatabaseHelper;
private ListView mListView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_data);
mListView = (ListView) findViewById(R.id.listView);
mDatabaseHelper = new DatabaseHelper(this);
populateListView();
}
private void populateListView() {
Log.d(TAG, "populateListView: Displaying data in the ListView.");
Cursor data = mDatabaseHelper.getData();
class Model {
String name;
String desc;
int price;
}
ArrayList< Model> listData = new ArrayList<>();
while(data.moveToNext()){
Model model = new Model();
model.name = data.getString(1);
model.desc = data.getString(2);
model.price = data.getInt(3);
listData.add(model); }
ListAdapter adapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, listData);
mListView.setAdapter(adapter);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Model model = (Model)adapterView.getItemAtPosition(i);
String name = model.name;
String des = model.des;
String pri = model.pri;
Log.d(TAG, "onItemClick: You Clicked on " + name);
Cursor data = mDatabaseHelper.getItemID(name, des, pri); //get the id associated with these
int itemID = -1;
while(data.moveToNext()){
itemID = data.getInt(0);
}
if(itemID > -1){
Log.d(TAG, "onItemClick: The ID is: " + itemID);
Intent intent = new Intent(ListDataActivity.this, EditDataActivity.class);
Bundle extras = new Bundle();
extras.putInt("id",itemID);
extras.putString("name",name);
extras.putString("description",des);
extras.putString("price",pri);
intent.putExtras(extras);
startActivity(intent);
}
else{
toastMessage("No ID associated with that name");
}
}
});
}
private void toastMessage(String message){
Toast.makeText(this,message, Toast.LENGTH_SHORT).show();
}
}
Logcat:
2019-04-11 10:51:34.331 32717-32717/? I/art: Late-enabling -Xcheck:jni
2019-04-11 10:51:34.351 32717-32717/? D/TidaProvider: TidaProvider()
2019-04-11 10:51:34.364 32717-32717/com.example.saveanddisplaysql W/ReflectionUtils: java.lang.NoSuchMethodException: android.os.MessageQueue#enableMonitor()#bestmatch
at miui.util.ReflectionUtils.findMethodBestMatch(ReflectionUtils.java:338)
at miui.util.ReflectionUtils.findMethodBestMatch(ReflectionUtils.java:375)
at miui.util.ReflectionUtils.callMethod(ReflectionUtils.java:800)
at miui.util.ReflectionUtils.tryCallMethod(ReflectionUtils.java:818)
at android.os.BaseLooper.enableMonitor(BaseLooper.java:47)
at android.os.Looper.prepareMainLooper(Looper.java:112)
at android.app.ActivityThread.main(ActivityThread.java:6221)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
Your "listData" ArrayList is a String type array list. So you can only add Strings in it. You need to create a class like
class Model {
String name;
String desc;
int price;
}
Then create array list of your model.
ArrayList< Model> listData = new ArrayList<>();
Then pass that model ArrayList to adapter and can get as well whenever needed.

Retaining ListView data after leaving Android acitivity

I am new to Android Studio. I am trying to use a ListView where the user can add items to a list. But when the user changes or closes the activity I want the items to come back as they were the last time the user saw them. I am not too familiar with the activity LifeCycle and how to use it yet so any resource or help is appreciated. Thanks. Here is my code:
package com.example.listviewtest;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity<i> extends AppCompatActivity {
private List nameArr;
private String textToAdd;
//input textbox
private EditText stuff;
// Add player names and scores to the list
private ListView score_lv;
//Append
private ArrayAdapter<String> arrayAdapter1;
//Clear Scores button
private Button updateButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
nameArr = new ArrayList<Object>();
stuff = (EditText)findViewById(R.id.editText);
score_lv = (ListView) findViewById(R.id.theList);
arrayAdapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, nameArr);
updateButton = (Button) findViewById(R.id.addButton);
updateButton.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v) {
nameArr.add(stuff.getText().toString());
//get data from other activity
textToAdd = getIntent().getExtras().getString("textData");
score_lv.setAdapter(arrayAdapter1);
}
});
final Button nextAct = (Button) findViewById(R.id.toNext);
nextAct.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v) {
Intent j = new Intent(MainActivity.this, Main2Activity.class);
startActivity(j);
}
}
);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Edit:
I was able to get the List updated using FileInputStream and FileOutputStream (I am trying to write to the Internal Storage). Because this app has 2 activites, when I switch to the other activity and go back to this one, the List and all its items remain. However, when I close the app entirely and then reopen the app, it seems that all the items in the list disappear. How do I make it stay using the FileI/OStreams (I know there is other methods like SQLite and such but I am trying to challenge myself by using other methods). Here is my updated code so far (thanks again to all for all of your help):
package com.example.listviewtest;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class MainActivity<i> extends AppCompatActivity {
private static final List nameArr = new ArrayList<Object>();
//input textbox
private EditText stuff;
// Add player names and scores to the list
private ListView score_lv;
//Append
private ArrayAdapter<String> arrayAdapter1;
//Clear Scores button
private Button updateButton;
private static final String fileName = "scores";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
stuff = (EditText)findViewById(R.id.editText);
score_lv = (ListView) findViewById(R.id.theList);
arrayAdapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, nameArr);
score_lv.setAdapter(arrayAdapter1);
//button to update the ListView
updateButton = (Button) findViewById(R.id.addButton);
updateButton.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v) {
//write data to the internal phone app File
try{
FileOutputStream fileOS = openFileOutput("scores", MODE_PRIVATE);
OutputStreamWriter osw = new OutputStreamWriter(fileOS);
try{
osw.write(stuff.getText().toString());
osw.flush();
osw.close();
Toast.makeText(getBaseContext(),"Scores Saved to "+getFilesDir() + "/", Toast.LENGTH_LONG).show();
}catch(IOException e){
e.printStackTrace();
}
}catch (FileNotFoundException e){
e.printStackTrace();
}
//read data from Saved File to update the ListView
nameArr.add(readFile("scores"));
score_lv.setAdapter(arrayAdapter1);
}
});
//button to go to the next Activity
final Button nextAct = (Button) findViewById(R.id.toNext);
nextAct.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v) {
Intent j = new Intent(MainActivity.this, Main2Activity.class);
startActivity(j);
}
}
);
}
//as soon as this Activity starts, we read from the Output File
public String readFile(String file){
StringBuilder text = new StringBuilder();
try{
FileInputStream fis = openFileInput(file);
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
String line;
while((line = reader.readLine()) != null){
text.append(line);
}
reader.close();
}catch(Exception e){
e.printStackTrace();
Toast.makeText(MainActivity.this,"Error reading file!",Toast.LENGTH_LONG).show();
}
return text.toString();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
So I added a Clear button but I was able to save multiple lines in the "scores" file that I saved in the internal device storage. When I close the app or go to the other activity and go back to this MainActivity with the ListView the information remains (because it reads directly from the "scores" file). The only thing is that it updates the 1 and only ListView item. I used nameArr.clear(); to clear the ListView everytime and the nameArr.clear(); and text.append('\n'); to read and write to the file so that each Text Input by the User appears the way I want them to (as a list). So here is my final code:
public class MainActivity<i> extends AppCompatActivity {
private static final List nameArr = new ArrayList<Object>();
//input textbox
private EditText stuff;
// Add player names and scores to the list
private ListView score_lv;
//Append
private ArrayAdapter<String> arrayAdapter1;
//Clear Scores button
private Button updateButton;
private static final String fileName = "scores";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
stuff = (EditText)findViewById(R.id.editText);
score_lv = (ListView) findViewById(R.id.theList);
arrayAdapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, nameArr);
nameArr.clear();
nameArr.add(readFile(fileName));
score_lv.setAdapter(arrayAdapter1);
//button to update the ListView
updateButton = (Button) findViewById(R.id.addButton);
updateButton.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v) {
//write data to the internal phone app File
try{
FileOutputStream fileOS = openFileOutput(fileName, MODE_APPEND);
OutputStreamWriter osw = new OutputStreamWriter(fileOS);
try{
osw.write("\n");
osw.write(stuff.getText().toString());
osw.flush();
osw.close();
Toast.makeText(getBaseContext(),"Scores Saved to "+getFilesDir() + "/", Toast.LENGTH_LONG).show();
}catch(IOException e){
e.printStackTrace();
}
}catch (FileNotFoundException e){
e.printStackTrace();
}
//read data from Saved File to update the ListView with ALL items from the file
nameArr.clear();
nameArr.add(readFile(fileName));
score_lv.setAdapter(arrayAdapter1);
}
});
//button to go to the next Activity
final Button nextAct = (Button) findViewById(R.id.toNext);
nextAct.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v) {
Intent j = new Intent(MainActivity.this, Main2Activity.class);
startActivity(j);
}
}
);
//delete file and clear ListView button
final Button clearB = (Button) findViewById(R.id.clearButton);
clearB.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v) {
deleteFile(fileName);
Toast.makeText(getBaseContext(), "List Cleared", Toast.LENGTH_LONG).show();
//clear list
score_lv.setAdapter(null);
}
}
);
}
//as soon as this Activity starts, we read from the Output File
public String readFile(String file){
StringBuilder text = new StringBuilder();
try{
FileInputStream fis = openFileInput(file);
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
String line;
while((line = reader.readLine()) != null){
text.append(line);
text.append('\n');
}
reader.close();
}catch(Exception e){
e.printStackTrace();
Toast.makeText(MainActivity.this,"Error reading file!",Toast.LENGTH_LONG).show();
}
return text.toString();
}
#rodgy, save your data to non-volatile memory, then read the data when you load the application.
try ths code
private List<String> nameArr = new ArrayList<>();
private static SharedPreferences sharedPreferences = context.getSharedPreferences("PREFS_NAME", Context.MODE_PRIVATE);
private static SharedPreferences.Editor editor = sharedPreferences.edit();
#how to use
// save data
setToList("1", nameArr);
// get data
nameArr = getList("1");
// save to sharedPreferences
public void setList(String key, List<String> list) {
String json = new Gson().toJson(list);
editor.putString(key, json);
editor.commit();
}
// read from sharedPreferences
public List<String> getList(String key){
List<String> result = new ArrayList<>();
String serObject = sharedPreferences.getString(key, null);
if (serObject != null){
Type type = new TypeToken<List<String>>(){}.getType();
result = new Gson().fromJson(serObject, type);
}
return result;
}

android switch intent dynamically

I am trying to create a main menu activity in android which dynamically selects the activity destination from its position on the page.
MainMenu.java
package com.verscreative.BowlTrack;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
public class MainMenu extends SherlockActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
GridView gridview = (GridView) findViewById(R.id.grid);
gridview.setAdapter(new HomeMenuAdapter());
gridview.setPadding(50, 40, 50, 40);
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
//Activities That are invoked by the click
String[] mActivitiesIds = {
getString(R.string.menu_launch_0),
getString(R.string.menu_launch_1),
getString(R.string.menu_launch_2),
getString(R.string.menu_launch_3),
getString(R.string.menu_launch_4),
getString(R.string.menu_launch_5)
};
String packageName = "com.verscreative.BowlTrack";
String className = mActivitiesIds[position]+".class";
//TODO: Switch Toast To Activity Intent
Intent i = new Intent();
i.setClassName(packageName, className);
try{
startActivity(i);
}catch(Exception e){
Toast t = Toast.makeText(getApplicationContext(), "Cannot Find Activity", Toast.LENGTH_LONG);
t.show();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(com.actionbarsherlock.view.MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
activateSettings();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void activateSettings(){
Intent i = new Intent(this, SettingsActivity.class);
startActivity(i);
}
public class HomeMenuAdapter extends BaseAdapter {
public HomeMenuAdapter() {
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
TextView tv;
if (convertView == null) {
tv = new TextView(getApplicationContext());
tv.setGravity(Gravity.CENTER | Gravity.BOTTOM);
tv.setPadding(0, 10, 0, 10);
} else {
tv = (TextView) convertView;
}
tv.setCompoundDrawablesWithIntrinsicBounds(0, mThumbIds[position], 0, 0);
tv.setText(mTextIds[position]);
tv.setHeight(300);
tv.setTextColor(Color.WHITE);
return tv;
}
// references to our images
private Integer[] mThumbIds = {
android.R.drawable.ic_menu_add,
android.R.drawable.ic_menu_view,
android.R.drawable.ic_menu_info_details,
android.R.drawable.ic_menu_close_clear_cancel,
android.R.drawable.ic_menu_close_clear_cancel,
android.R.drawable.ic_menu_preferences
};
private String[] mTextIds = {
getString(R.string.menu_item_0),
getString(R.string.menu_item_1),
getString(R.string.menu_item_2),
getString(R.string.menu_item_3),
getString(R.string.menu_item_4),
getString(R.string.menu_item_5)
};
}
}
However whatever I do it always says "Cannot Find Activity".
If I change:
String packageName = "com.verscreative.BowlTrack";
String className = mActivitiesIds[position]+".class";
Intent i = new Intent();
i.setClassName(packageName, className);
to for example:
Context packageName = MainMenu.this;
Class<ViewGamesActivity> className = ViewGamesActivity.class;
Intent i = new Intent();
i.setClass(packageName, className);
It works fine, but all options do the same thing!
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">BowlTrack</string>
<string name="action_settings">Settings</string>
<string name="menu_item_0">Add New Game</string>
<string name="menu_item_1">View Games</string>
<string name="menu_item_2">Stats</string>
<string name="menu_item_3">3-Not</string>
<string name="menu_item_4">4-Not</string>
<string name="menu_item_5">Settings</string>
<string name="menu_launch_0">NewGameActivity</string>
<string name="menu_launch_1">ViewGamesActivity</string>
<string name="menu_launch_2">ViewOverallActivity</string>
<string name="menu_launch_3">3-Not</string>
<string name="menu_launch_4">4-Not</string>
<string name="menu_launch_5">SettingsActivity</string>
<color name="black">#000000</color>
<color name="bwtk">#88078b</color>
<string name="title_activity_view_games">View Games</string>
</resources>
ViewGamesActivity.java
package com.verscreative.BowlTrack;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
public class ViewGamesActivity extends SherlockActivity {
public class ViewGames extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static final String url_all_products = "http://api.androidhive.info/android_connect/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_games);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid))
.getText().toString();
// TODO: Starting new intent
// Intent in = new Intent(getApplicationContext(),
// EditProductActivity.class);
// sending pid to next activity
// in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response
// back
// startActivityForResult(in, 100);
}
});
}
// Response from Edit Product Activity
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ViewGamesActivity.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products,
"GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key =>
// value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// TODO: no products found
// Launch Add New product Activity
// Intent i = new Intent(getApplicationContext(),
// NewProductActivity.class);
// Closing all previous activities
// i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
ViewGamesActivity.this, productsList,
R.layout.list_item, new String[] { TAG_PID,
TAG_NAME }, new int[] { R.id.pid,
R.id.name });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
}
Thanks to jimpanzer and sherif-elkhatib, I have combined your comments to find the answer.
The Answer is Changing:
String className = mActivitiesIds[position]+".class";
to this:
String className = "com.verscreative.BowlTrack."+mActivitiesIds[position];
I don't think you need to specify the .class
Try this
String className = mActivitiesIds[position];
Otherwise, a more efficient solution would be to have a 2D array as such :
Object[][] mActivitiesIds =
{
{ getString(R.string.menu_launch_0), Activity1.class }
{ getString(R.string.menu_launch_1), Activity1.class }
{ getString(R.string.menu_launch_2), Activity1.class }
{ getString(R.string.menu_launch_3), Activity1.class }
{ getString(R.string.menu_launch_4), Activity1.class }
{ getString(R.string.menu_launch_5) Activity1.class }
};
Then simply use mActivitiesIds[n][1] to get the class...

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