I recently wanted to develop a shopping list app and i followed this tutorial, but in this tutorial the tutor shows that his added items are stored but I followed the same process but when I close and reopen the app the added items are gone. what can be done to fix this?
here is my program code:
package com.dopenets.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import android.app.AlertDialog;
import android.widget.EditText;
import android.content.DialogInterface;
import android.content.Context;
import android.content.SharedPreferences;
import android.app.Activity;
import android.widget.Toast;
import android.widget.AdapterView;
import android.widget.TextView;
import android.view.View;
public class MainActivity extends AppCompatActivity {
ArrayList<String> shoppingList = null;
ArrayAdapter<String> adapter = null;
ListView lv = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
shoppingList = getArrayVal(getApplicationContext());
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, shoppingList);
lv = (ListView) findViewById(R.id.listView);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView parent, View view, final int position, long id) {
String selectedItem = ((TextView) view).getText().toString();
if (selectedItem.trim().equals(shoppingList.get(position).trim())) {
removeElement(selectedItem, position);
} else {
Toast.makeText(getApplicationContext(),"Error Removing Element", Toast.LENGTH_LONG).show();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_add){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Add Item");
final EditText input = new EditText(this);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
shoppingList.add(preferredCase(input.getText().toString()));
Collections.sort(shoppingList);
lv.setAdapter(adapter);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
return true;
}
return super.onOptionsItemSelected(item);
}
public static String preferredCase(String original)
{
if (original.isEmpty())
return original;
return original.substring(0, 1).toUpperCase() + original.substring(1).toLowerCase();
}
public static void storeArrayVal( ArrayList<String> inArrayList, Context context)
{
Set<String> WhatToWrite = new HashSet<String>(inArrayList);
SharedPreferences WordSearchPutPrefs = context.getSharedPreferences("dbArrayValues", Activity.MODE_PRIVATE);
SharedPreferences.Editor prefEditor = WordSearchPutPrefs.edit();
prefEditor.putStringSet("myArray", WhatToWrite);
prefEditor.commit();
}
public static ArrayList getArrayVal( Context dan)
{
SharedPreferences WordSearchGetPrefs = dan.getSharedPreferences("dbArrayValues",Activity.MODE_PRIVATE);
Set<String> tempSet = new HashSet<String>();
tempSet = WordSearchGetPrefs.getStringSet("myArray", tempSet);
return new ArrayList<String>(tempSet);
}
public void removeElement(String selectedItem, final int position){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Remove " + selectedItem + "?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
shoppingList.remove(position);
Collections.sort(shoppingList);
storeArrayVal(shoppingList, getApplicationContext());
lv.setAdapter(adapter);
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
}
It appears that you are not calling the storeArrayVal method when an item is added, so nothing is ever stored.
Related
I have a problem in my code. I want to add items to a listview from another acivity onclickButton, but it only adds one item. And if I reapeat it, it only replaces the last added item. I can't figure out whats the problem some help please.
my code :
MainActivity:
package com.example.nasreddine.mtodubled; // project package
import android.app.AlertDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity; //imports statements
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import android.content.DialogInterface;
public class MainActivity extends AppCompatActivity {
AlertDialog.Builder alert;
public ArrayList<City> listItems;
ArrayAdapter adapter;
ListView cityListView;
#Override
protected void onCreate(Bundle savedInstanceState) { //onCreate State
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listItems=new ArrayList<>();
adapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1,listItems);
//Displaying Data on ListView
cityListView=(ListView)findViewById(R.id.cityListView);
cityListView.setAdapter(adapter);
registerForContextMenu(cityListView);
listItems.add(new City("a","b","","","","",""));
listItems.add(new City("v","c","","","","",""));
updateListView();
cityListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
cityListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
alert.setTitle("Delete Item from list");
alert.setMessage("Are you sure you want to delete?");
alert.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
listItems.remove(position);
adapter.notifyDataSetChanged();
}
});
alert.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alert.show();
return true;
}
});
}
public void updateListView() {
Bundle bundle = getIntent().getExtras();
Intent intent=getIntent();
if (bundle != null) {
City a=new City(intent.getStringExtra("city"),intent.getStringExtra("country"),"/","/","/","/","/");
//listItems.add(a);
adapter.add(a);
adapter.notifyDataSetChanged();
}
}
public boolean onOptionsItemSelected(MenuItem item){
if (item.getItemId()==R.id.action_add){
Intent intent=new Intent(MainActivity.this,AddCity.class);
startActivity(intent);
return (true);
}
return (super.onOptionsItemSelected(item));
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main,menu);
return super.onCreateOptionsMenu(menu);
}
}
AddCity.java
package com.example.nasreddine.mtodubled;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class AddCity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_city);
Button addButton=(Button)findViewById(R.id.addButton);
final TextView cityAddText=(TextView)findViewById(R.id.cityAddText);
final TextView countryAddText=(TextView)findViewById(R.id.countryAddText);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String city= cityAddText.getText().toString();
String country=countryAddText.getText().toString();
Intent intent =new Intent(AddCity.this,MainActivity.class);
intent.putExtra("city",city);
intent.putExtra("country",country);
startActivity(intent);
}
});
}
}
In your MainActivity.class start the AddCity.class using startActivityForResult().
public boolean onOptionsItemSelected(MenuItem item){
if (item.getItemId()==R.id.action_add){
Intent intent=new Intent(MainActivity.this,AddCity.class);
startActivityForResult(intent, requestCode); //ex: requestCode = 1
return (true);
}
return (super.onOptionsItemSelected(item));
}
After that in AddCity change add button click listener code with below:
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String city= cityAddText.getText().toString();
String country=countryAddText.getText().toString();
Intent intent =new Intent();
intent.putExtra("city",city);
intent.putExtra("country",country);
setResult(RESULT_OK, intent);
finish();
}
});
After that in MainActivity's onActivityResult() get data and add it to list. Also remove updatListView() method from MainActivity.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
getActivity().invalidateOptionsMenu();
if (resultCode == Activity.RESULT_OK) {
if (data != null) {
City a=new City(data.getStringExtra("city"),data.getStringExtra("country"),"/","/","/","/","/");
listItems.add(a);
adapter.add(a);
adapter.notifyDataSetChanged();
}
}
}
}
You are restarting the MainActivity from AddCity Activity.
Rather than doing this, you need to start AddCity Activity, using method startActivityForResult().
And in AddCity Activity, rather than starting new MainActivity, you need to use setResult() method to send data to previous activity.
Also you need to override the onActivityResult method in MainActivity Class to owner the response from AddCity Activity.
Cheers!!!
Here is the code:
Class Main Activity,
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity
{
AlertDialog.Builder alert;
public List<City> listItems;
ArrayAdapter<City> adapter;
ListView cityListView;
#Override
protected void onCreate(Bundle savedInstanceState)
{ //onCreate State
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listItems = new ArrayList<>();
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listItems);
//Displaying Data on ListView
Button addButton = (Button) findViewById(R.id.addButton);
addButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
startActivityForResult(new Intent(MainActivity.this, AddCity.class), 1);
}
});
cityListView = (ListView) findViewById(R.id.cityListView);
cityListView.setAdapter(adapter);
registerForContextMenu(cityListView);
listItems.add(new City("a", "b"));
listItems.add(new City("v", "c"));
updateListView();
}
public void updateListView()
{
Bundle bundle = getIntent().getExtras();
Intent intent = getIntent();
if(bundle != null)
{
City a = new City(intent.getStringExtra("city"), intent.getStringExtra("country"));
//listItems.add(a);
adapter.add(a);
adapter.notifyDataSetChanged();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent)
{
super.onActivityResult(requestCode, resultCode, intent);
if(requestCode == 1 && resultCode == RESULT_OK)
{
City a = new City(intent.getStringExtra("city"), intent.getStringExtra("country"));
//listItems.add(a);
adapter.add(a);
adapter.notifyDataSetChanged();
}
}
}
Class Add City,
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class AddCity extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.add_city);
Button addButton = (Button) findViewById(R.id.addButton);
final TextView cityAddText = (TextView) findViewById(R.id.cityAddText);
final TextView countryAddText = (TextView) findViewById(R.id.countryAddText);
addButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
String city = cityAddText.getText().toString();
String country = countryAddText.getText().toString();
Intent intent = new Intent();
intent.putExtra("city", city);
intent.putExtra("country", country);
setResult(RESULT_OK, intent);
}
});
}
}
Hopefully, this will help you.
Cheers!!!
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I have been looking around for the answer but no luck on this. to resume
the id of my button is correct
Activity names are correct, but for some reason the Bundle is returning null and crashing my App, This is my Main Activity, please help.
Check the OnClick Listener I think I am using the correct form
Main Activity
package com.example.carlos.application1;
import android.widget.Button;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends ActionBarActivity {
public final static String EXTRA_MESSAGE = "MESSAGE";
private ListView obj;
DBHelper mydb;
int status = 0;
Button hp_1, HP2, fo, previous, home, next,MZ,Control,show;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mydb = new DBHelper(this);
ArrayList array_list = mydb.getAllCotacts();
ArrayAdapter arrayAdapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1, array_list);
obj = (ListView)findViewById(R.id.listView1);
obj.setAdapter(arrayAdapter);
obj.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
int id_To_Search = arg2 + 1;
Bundle dataBundle = new Bundle();
dataBundle.putInt("id", id_To_Search);
Intent intent = new Intent(getApplicationContext(), DisplayValues.class);
intent.putExtras(dataBundle);
startActivity(intent);
}
});
hp_1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
status = 1;
Bundle bundle = new Bundle();
bundle.putInt("status", status);
Intent intent = new Intent(MainActivity.this, DisplayValues.class);
intent.putExtras(bundle);
startActivity(intent);
}
});
}
#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){
super.onOptionsItemSelected(item);
switch(item.getItemId())
{
case R.id.item1:Bundle dataBundle = new Bundle();
dataBundle.putInt("id", 0);
Intent intent = new Intent(getApplicationContext(),DisplayValues.class);
intent.putExtras(dataBundle);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public boolean onKeyDown(int keycode, KeyEvent event) {
if (keycode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
}
return super.onKeyDown(keycode, event);
}
}
you haven't assigned anything to hp_1 so its value is NULL and that is the problem. You need to do the following:
hp_1 = (Button) findViewById(...);
hp_1.setOnClickListener(new View.OnClickListener() {
...
I'm making an app that will let users add their school subjects.
Before i continue let me give you my code:
MainActivity:
package cannon.gaming.mymarks;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends ActionBarActivity {
TextView textSubject;
String SUBJECT, PASS;
Context ctx = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
/*Button buttonAdd = (Button) findViewById(R.id.buttonAdd);
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), RegisterActivity.class);
intent.setFlags(intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivityForResult(intent, 0);
}
});*/
Button buttonAdd = (Button) findViewById(R.id.buttonAdd);
textSubject = (TextView) findViewById(R.id.textSubject);
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showInputDialog();
}
});
}
protected void showInputDialog() {
// get prompts.xml view
LayoutInflater layoutInflater = LayoutInflater.from(MainActivity.this);
View promptView = layoutInflater.inflate(R.layout.activity_dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
alertDialogBuilder.setView(promptView);
final EditText editText = (EditText) promptView.findViewById(R.id.edittext);
// setup a dialog window
alertDialogBuilder.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
SUBJECT = editText.getText().toString();
PASS = "0";
DatabaseOperations DB = new DatabaseOperations(ctx);
DB.putInformation(DB, SUBJECT, PASS);
Toast.makeText(getBaseContext(), "Subject added", Toast.LENGTH_SHORT).show();
finish();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create an alert dialog
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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);
}
}
TableData:
package cannon.gaming.mymarks;
import android.provider.BaseColumns;
/**
* Created by Asuspc on 01/07/2015.
*/
public class TableData {
public TableData()
{
}
public static abstract class TableInfo implements BaseColumns
{
public static final String USER_NAME = "user_name";
public static final String USER_PASS = "user_pass";
public static final String DATABASE_NAME = "user_info";
public static final String TABLE_NAME = "reg_info";
}
}
DatabaseOperations:
package cannon.gaming.mymarks;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
/**
* Created by Asuspc on 01/07/2015.
*/
public class DatabaseOperations extends SQLiteOpenHelper {
public static final int database_version = 1;
public String CREATE_QUERY = "CREATE TABLE "+ TableData.TableInfo.TABLE_NAME+"("+ TableData.TableInfo.USER_NAME+" TEXT,"+ TableData.TableInfo.USER_PASS+" TEXT);";
public DatabaseOperations(Context context) {
super(context, TableData.TableInfo.DATABASE_NAME, null, database_version);
Log.d("Database Operations", "Database created");
}
#Override
public void onCreate(SQLiteDatabase sdb)
{
sdb.execSQL(CREATE_QUERY);
Log.d("Database Operations", "Table created");
}
#Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2)
{
}
public void putInformation(DatabaseOperations dop,String name, String pass)
{
SQLiteDatabase SQ = dop.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(TableData.TableInfo.USER_NAME, name);
cv.put(TableData.TableInfo.USER_PASS, pass);
long k = SQ.insert(TableData.TableInfo.TABLE_NAME, null, cv);
Log.d("Database Operations", "One row inserted");
}
public Cursor getInformation(DatabaseOperations dop)
{
SQLiteDatabase SQ = dop.getReadableDatabase();
String[] columns = {TableData.TableInfo.USER_NAME, TableData.TableInfo.USER_PASS};
Cursor CR = SQ.query(TableData.TableInfo.TABLE_NAME, columns, null, null, null, null, null);
return CR;
}
}
Now let me explain.
When I press the "buttonAdd" button it will let me enter the subject name obviously, and save it in database.
But what I can't make is, I want to display all database on MainActivity.
And it should be like this:
names of subjects on the left side,
average of those subjects on the right side (the string PASS should be that average, that's why it is 0 when you first add the subject).
And I want to make each of those subjects clickable, so when you click it it should show you all marks from that subject and let you add or remove them.
Now, I guess, displaying data shouldn't be so hard, but still I need your help.
But making each subject clickable I really have no idea how.
And each subject having its own marks, I don't know, does it mean new activity for every new subject or new database or what?
EDIT:
MainActivity now:
package cannon.gaming.mymarks;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Build;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends ActionBarActivity {
String SUBJECT, PASS;
Context CTX = this;
private SimpleCursorAdapter adapter;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
/*Button buttonAdd = (Button) findViewById(R.id.buttonAdd);
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), RegisterActivity.class);
intent.setFlags(intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivityForResult(intent, 0);
}
});*/
Button buttonAdd = (Button) findViewById(R.id.buttonAdd);
displayListView();
buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showInputDialog();
}
});
}
protected void showInputDialog() {
// get prompts.xml view
LayoutInflater layoutInflater = LayoutInflater.from(MainActivity.this);
View promptView = layoutInflater.inflate(R.layout.activity_dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
alertDialogBuilder.setView(promptView);
final EditText editText = (EditText) promptView.findViewById(R.id.edittext);
// setup a dialog window
alertDialogBuilder.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
SUBJECT = editText.getText().toString();
PASS = "0";
DatabaseOperations DB = new DatabaseOperations(CTX);
DB.putInformation(DB, SUBJECT, PASS);
Toast.makeText(getBaseContext(), "Subject added", Toast.LENGTH_SHORT).show();
adapter.notifyDataSetChanged();
displayListView();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create an alert dialog
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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);
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void displayListView()
{
DatabaseOperations DOP = new DatabaseOperations(CTX);
Cursor CR = DOP.getInformation(DOP);
CR.moveToFirst();
// The desired columns to be bound
String[] columns = new String[]{
TableData.TableInfo.USER_NAME,
TableData.TableInfo.USER_PASS
};
// the XML defined views which the data will be bound to
int[] to = new int[]{
R.id.code,
R.id.name,
};
adapter = new SimpleCursorAdapter(
this, R.layout.activity_login,
CR,
columns,
to,
0);
ListView listView = (ListView) findViewById(R.id.listView);
// Assign adapter to ListView
listView.setAdapter(adapter);
}
}
To display data, you should use ListView and CursorAdapter.
Here is sample code for you: http://www.mysamplecode.com/2012/07/android-listview-cursoradapter-sqlite.html
In that sample code, you can see:
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
// Get the cursor, positioned to the corresponding row in the result set
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
// Get the state's capital from this row in the database.
String countryCode =
cursor.getString(cursor.getColumnIndexOrThrow("code"));
Toast.makeText(getApplicationContext(),
countryCode, Toast.LENGTH_SHORT).show();
}
});
OnItemClickListener will help you to handle when a item in the listview is clicked.
Hope this will help you.
I'm trying to create the favorites list from Json Objects which I received by URL.
When I got Json array, I defined methods OnItemLongClickListener and OnItemClickListener that get different things:
The OnItemClickListener method has to open another activity with description of product
The OnItemLongClickListener method has to add product to favorite list
The Problem that method OnItemClickListener which I defined in MainActivity is override method OnItemLongClickListener which I defined in FragmentActivty and the method OnItemLongClickListener doesn't work at all then I tried to define both methods in FragmentActivity but after that both methods don't work at all.
Is there any way to determine this problem?
Main Activity:
package com.boom.kayakapp.activities;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.boom.kayakapp.R;
import com.boom.kayakapp.adapters.AirlinesAdapter;
import com.boom.kayakapp.controllers.AppController;
import com.boom.kayakapp.fragment.AirlinesFragment;
import com.boom.kayakapp.fragment.FavoriteFragment;
import com.boom.kayakapp.model.Airlines;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends ActionBarActivity {
private Fragment contentFragment;
AirlinesFragment airlinesFragment;
FavoriteFragment favoriteFragment;
// JSON Node names
public static final String TAG_NAME = "name";
public static final String TAG_PHONE = "phone";
public static final String TAG_SITE = "site";
public static final String TAG_LOGO = "logoURL";
public static final String TAG_CODE = "code";
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
// Airlines json url
private static final String url = "https://www.kayak.com/h/mobileapis/directory/airlines";
public ProgressDialog pDialog;
public List<Airlines> airlinesList = new ArrayList<Airlines>();
public ListView listView;
public AirlinesAdapter adapter;
#Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
listView = (ListView) findViewById(R.id.list);
adapter = new AirlinesAdapter(this, airlinesList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// Listview on item click listener
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String phone = ((TextView) view.findViewById(R.id.phone))
.getText().toString();
String site = ((TextView) view.findViewById(R.id.site))
.getText().toString();
String logoURL = String.valueOf(((ImageView) view.findViewById(R.id.logoURL)));
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_PHONE, phone);
in.putExtra(TAG_SITE, site);
in.putExtra(TAG_LOGO, logoURL);
startActivity(in);
}
});
// changing action bar color
getSupportActionBar().setBackgroundDrawable(
new ColorDrawable(Color.parseColor("#1b1b1b")));
// Creating volley request obj
JsonArrayRequest airlinesReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Airlines airlines = new Airlines();
airlines.setName(obj.getString("name"));
airlines.setLogoURL(obj.getString("logoURL"));
airlines.setPhone(obj.getString("phone"));
airlines.setCode(obj.getInt("code"));
airlines.setSite(obj.getString("site"));
// adding airlines to movies array
airlinesList.add(airlines);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(airlinesReq);
FragmentManager fragmentManager = getSupportFragmentManager();
/*
* This is called when orientation is changed.
*/
if (savedInstanceState != null) {
if (savedInstanceState.containsKey("content")) {
String content = savedInstanceState.getString("content");
if (content.equals(FavoriteFragment.ARG_ITEM_ID)) {
if (fragmentManager.findFragmentByTag(FavoriteFragment.ARG_ITEM_ID) != null) {
setFragmentTitle(R.string.favorites);
contentFragment = fragmentManager
.findFragmentByTag(FavoriteFragment.ARG_ITEM_ID);
}
}
}
if (fragmentManager.findFragmentByTag(AirlinesFragment.ARG_ITEM_ID) != null) {
airlinesFragment = (AirlinesFragment) fragmentManager
.findFragmentByTag(AirlinesFragment.ARG_ITEM_ID);
contentFragment = airlinesFragment;
}
} else {
airlinesFragment = new AirlinesFragment();
// setFragmentTitle(R.string.app_name);
switchContent(airlinesFragment, AirlinesFragment.ARG_ITEM_ID);
}
}
#Override
public void onDestroy () {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onSaveInstanceState(Bundle outState) {
if (contentFragment instanceof FavoriteFragment) {
outState.putString("content", FavoriteFragment.ARG_ITEM_ID);
} else {
outState.putString("content", AirlinesFragment.ARG_ITEM_ID);
}
super.onSaveInstanceState(outState);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_favorites:
setFragmentTitle(R.string.favorites);
favoriteFragment = new FavoriteFragment();
switchContent(favoriteFragment, FavoriteFragment.ARG_ITEM_ID);
return true;
}
return super.onOptionsItemSelected(item);
}
public void switchContent(Fragment fragment, String tag) {
FragmentManager fragmentManager = getSupportFragmentManager();
while (fragmentManager.popBackStackImmediate()) ;
if (fragment != null) {
FragmentTransaction transaction = fragmentManager
.beginTransaction();
transaction.replace(R.id.content_frame, fragment, tag);
//Only FavoriteFragment is added to the back stack.
if (!(fragment instanceof AirlinesFragment)) {
transaction.addToBackStack(tag);
}
transaction.commit();
contentFragment = fragment;
}
}
protected void setFragmentTitle(int resourseId) {
setTitle(resourseId);
getSupportActionBar().setTitle(resourseId);
}
/*
* We call super.onBackPressed(); when the stack entry count is > 0. if it
* is instanceof ProductListFragment or if the stack entry count is == 0, then
* we finish the activity.
* In other words, from ProductListFragment on back press it quits the app.
*/
#Override
public void onBackPressed() {
FragmentManager fm = getSupportFragmentManager();
if (fm.getBackStackEntryCount() > 0) {
super.onBackPressed();
} else if (contentFragment instanceof AirlinesFragment
|| fm.getBackStackEntryCount() == 0) {
finish();
}
}
}
FragmentActivity:
package com.boom.kayakapp.fragment;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import com.boom.kayakapp.R;
import com.boom.kayakapp.adapters.AirlinesAdapter;
import com.boom.kayakapp.model.Airlines;
import com.boom.kayakapp.util.SharedPreference;
import java.util.ArrayList;
import java.util.List;
public class AirlinesFragment extends Fragment implements OnItemClickListener, OnItemLongClickListener{
public static final String ARG_ITEM_ID = "airlines_list";
Activity activity;
ListView airlinesListView;
List<Airlines> airlines;
AirlinesAdapter airlinesAdapter;
public AirlinesFragment() {
airlines = new ArrayList<>();
}
SharedPreference sharedPreference;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = getActivity();
sharedPreference = new SharedPreference();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_list, container,
false);
findViewsById(view);
airlinesAdapter = new AirlinesAdapter(activity, airlines);
airlinesListView.setAdapter(airlinesAdapter);
airlinesListView.setOnItemClickListener(this);
airlinesListView.setOnItemLongClickListener(this);
return view;
}
private void findViewsById(View view) {
airlinesListView = (ListView) view.findViewById(R.id.list);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Airlines airlines = (Airlines) parent.getItemAtPosition(position);
Toast.makeText(activity, airlines.toString(), Toast.LENGTH_LONG).show();
}
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View view,
int position, long arg3) {
ImageView button = (ImageView) view.findViewById(R.id.favorite_button);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(activity, airlines.get(position));
Toast.makeText(activity,
activity.getResources().getString(R.string.add_favr),
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.heart_red);
} else {
sharedPreference.removeFavorite(activity, airlines.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.heart_grey);
Toast.makeText(activity,
activity.getResources().getString(R.string.remove_favr),
Toast.LENGTH_SHORT).show();
}
return true;
}
#Override
public void onResume() {
getActivity().setTitle(R.string.app_name);
super.onResume();
}
}
In my way I deleted definition both Methods from FavoriteFragment and defined it in MainActivity:
Json Array
listView = (ListView) findViewById(R.id.list);
adapterAirlines = new AirlinesAdapter(this, airlinesList);
listView.setAdapter(adapterAirlines);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// Listview OnItemClickListener
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String phone = ((TextView) view.findViewById(R.id.phone))
.getText().toString();
String site = ((TextView) view.findViewById(R.id.site))
.getText().toString();
String logoURL = String.valueOf(((ImageView) view.findViewById(R.id.logoURL)));
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_PHONE, phone);
in.putExtra(TAG_SITE, site);
in.putExtra(TAG_LOGO, logoURL);
startActivity(in);
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
ImageView button = (ImageView) view.findViewById(R.id.favorite_button);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(MainActivity.this, airlinesList.get(position));
Toast.makeText(MainActivity.this,
MainActivity.this.getResources().getString(R.string.add_favr),
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.heart_red);
} else {
sharedPreference.removeFavorite(MainActivity.this, airlinesList.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.heart_grey);
Toast.makeText(MainActivity.this,
MainActivity.this.getResources().getString(R.string.remove_favr),
Toast.LENGTH_SHORT).show();
}
return true;
}
});
now it works
I have an application that extends ActionBarActivity, but I'm using ListView and I need to implement OnItemClickListener and I'm not sure how to do this without extending ListActivity. Also I want to ask you: Moreover I have a button and I need to listen if the button is clicked or if an item in the list is clicked. I'm not pretty sure how to do this.
So I would really appreciate if you help me :)
Here is my code:
package com.src.vicnote;
import java.io.File;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.os.Build;
public class MainActivity extends ActionBarActivity {
Button newButton;
String path = Environment.getExternalStorageDirectory().toString()+"/VICNote";
String lastOfPath;
File f = new File(path);
File files[] = f.listFiles();
String[] theNamesOfFiles = new String[files.length + 1];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
theNamesOfFiles[0] = "Create new note";
for(int i = 1; i < theNamesOfFiles.length; i++) {
lastOfPath = files[i-1].toString().split("/")[files[i-1].toString().split("/").length-1];
theNamesOfFiles[i] = lastOfPath.replace(".txt","");
Log.d("Files", "String: " + theNamesOfFiles[i]);
}
ListView lv = (ListView) findViewById(R.id.notesList);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
theNamesOfFiles);
lv.setAdapter(adapter);
newButton = (Button) findViewById(R.id.buttonNew);
newButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent newNote = new Intent(MainActivity.this, NewNoteActivity.class);
startActivity(newNote);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
You can implement the OnItemClickListener interface and override onItemClick
lv.setAdapter(adapter);
lv.setOnItemClickListener( new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast.makeText(MainActivity.this.this, "List View row Clicked at"+position,Toast.LENGTH_SHORT).show();
}
});
If the button belongs to activity_main.xml then what you have
newButton.setOnClickListener(new View.OnClickListener()
is right
You can set item click listener for ListView using this code.
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position,
long arg3)
{
// it is used to get the clicked string
String theNamesOfFile = adapter.getItem(position);
}
});
I guess it can help you.