I have an error that I don't know why in my Galaxy Ace Samsung(Android 2.3.6) doesn't work but in my Motorola G (Android 4.4) works perfectly. The exception are so strange this is my code:
adapter = new SimpleCursorAdapter(this,R.layout.single_row_profession, cursor,from,to,0);
package com.orun.app;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.orun.database.DataBaseManager;
import com.orun.model.Profession;
import com.orun.s.SConnection;
public class ProfessionsActivity extends Activity {
public static SConnection sConnection;
public static DataBaseManager manager;
private static Cursor cursor;
private static ListView listView;
private static SimpleCursorAdapter adapter;
private static EditText etSearch;
private static ImageButton btSearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_professions);
SharedPreferences sharedPref = getSharedPreferences(getString(R.string.PREFERENCE_FILE_KEY), Context.MODE_PRIVATE);
Toast.makeText(getApplicationContext(), "Rol "+sharedPref.getString("ROL","Estudiante"),Toast.LENGTH_LONG).show();
manager = new DataBaseManager(this);
listView = (ListView) findViewById(R.id.listView);
etSearch = (EditText)findViewById(R.id.etSearch);
new LoadTask().execute();
cursor = manager.searchProfession(etSearch.getText().toString());
int[] to = new int[]{R.id.textCode, R.id.textName,R.id.textType};
String[] from = new String[]{"_id","name","type"};
try {
adapter = new SimpleCursorAdapter(this,R.layout.single_row_profession, cursor,from,to,0);
}catch (Exception e){
e.printStackTrace();
}
listView.setAdapter(adapter);
etSearch.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
new SearchTask().execute();
adapter.changeCursor(cursor);
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {}
public void onTextChanged(CharSequence s, int start, int before,
int count) {}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(ProfessionsActivity.this,PrincipalActivity.class);
int codeProfession = Integer.parseInt(((TextView)(view.findViewById(R.id.textCode))).getText().toString());
SharedPreferences sharedPref = getSharedPreferences(getString(R.string.PREFERENCE_FILE_KEY), Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("CODE_PROFESSION", codeProfession);
editor.commit();
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.professions, 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);
}
private class SearchTask extends AsyncTask<Void, Void, Void>{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
cursor = manager.searchProfession(etSearch.getText().toString());
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
}
private class LoadTask extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... params) {
try {
sConnection = new SConnection();
for(Profession p : sConnection.getPlansPreg())
manager.insertProfession(p.getCode(),p.getName(),"PRE");
for(Profession p : sConnection.getPlansPos())
manager.insertProfession(p.getCode(),p.getName(),"POS");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
Toast.makeText(getApplicationContext(),"Se han cargador todos los planes",Toast.LENGTH_SHORT).show();
}
}
}
The exception is: Cannot resolve constructor
'(Landroid/context/Context;ILandroid/database/Cursor;[Ljava/lang/String;[II)V
The constructor you are using was added in API level 11, so it's no wonder it doesn't exist in Android 2.3.6 (API level 10).
public SimpleCursorAdapter (Context context, int layout, Cursor c,
String[] from, int[] to, int flags) Added in API level 11
Standard constructor.
Parameters
context The context where the
ListView associated with this SimpleListItemFactory is running
layout resource identifier of a layout file that defines the views for this list item. The layout file should include at least those named views defined in "to"
c The database cursor. Can be null if the cursor is not available yet.
from A list of column names representing the data to bind to the UI. Can be null if the cursor is not available yet.
to The views that should display column in the "from" parameter. These should all be TextViews. The first N views in this list are given the values of the first N columns in the from parameter. Can be null if the cursor is not available yet.
flags Flags used to determine the behavior of the adapter, as per CursorAdapter(Context, Cursor, int).
See class reference.
Related
I'm trying to get favourite items in favourite list from main list.When i click on favourite icon in mainlist, favouritelist get updating but when i remove any favourite from favouritelist and trying to add more favourites from mainlist i get error index out of bound exception
MainActivity
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.Toast;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends AppCompatActivity implements RecyclerViewClickListener{
RecyclerView simpleListView;
static Context ctx;
String diseaseList[];
SharedPreference sharedPreference;
DiseaseAdapter da;
List<String> newDiseaseList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ctx=this;
sharedPreference = new SharedPreference();
diseaseList= new String[]{"Abscess",
"Allergies",
"Amnesia",
"Anemia",
"Andropause",
"Angina",
"Weight Loss"};
Arrays.sort(diseaseList);
newDiseaseList = Arrays.asList(diseaseList);
simpleListView= (RecyclerView)findViewById(R.id.simpleListView);
LinearLayoutManager lm=new LinearLayoutManager(MainActivity.this);
simpleListView.setLayoutManager(lm);
/* DividerItemDecoration di=new DividerItemDecoration(MainActivity.this,lm.getOrientation());
simpleListView.addItemDecoration(di);*/
da=new DiseaseAdapter(newDiseaseList,ctx,this);
simpleListView.setAdapter(da);
simpleListView.setHasFixedSize(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_favorites:
Intent i=new Intent(this,Favourite.class);
this.startActivity(i);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onResume() {
super.onResume();
da.notifyDataSetChanged();
}
#Override
public void recyclerViewListClicked(View view, int position) {
ImageView button = (ImageView) view.findViewById(R.id.imgbtn_favorite);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(ctx, newDiseaseList.get(position));
Toast.makeText(ctx,
"add to favourites",
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.star_colour);
} else {
sharedPreference.removeFavorite(ctx, newDiseaseList.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.ic_action_name);
Toast.makeText(ctx,
"removed from favourites",
Toast.LENGTH_SHORT).show();
}
}
}
Favourite.java
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.Collections;
import java.util.List;
public class Favourite extends AppCompatActivity implements RecyclerViewClickListener {
RecyclerView favoriteList;
SharedPreference sharedPreference;
List<String> favorites;
DiseaseAdapter diseaseAdapter;
static Context ctx;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favourite);
ctx=this;
sharedPreference = new SharedPreference();
favorites = sharedPreference.getFavorites(ctx);
Collections.sort(favorites);
favoriteList = (RecyclerView)findViewById(R.id.favListView);
LinearLayoutManager lm=new LinearLayoutManager(ctx);
favoriteList.setLayoutManager(lm);
favoriteList.setHasFixedSize(true);
if (favorites == null) {
showAlert(getResources().getString(R.string.no_favorites_items),
getResources().getString(R.string.no_favorites_msg));
} else {
if (favorites.size() == 0) {
showAlert(
getResources().getString(R.string.no_favorites_items),
getResources().getString(R.string.no_favorites_msg));
}
if (favorites != null) {
diseaseAdapter = new DiseaseAdapter(favorites,ctx,this);
favoriteList.setAdapter(diseaseAdapter);
}
}
}
public void showAlert(String title, String message) {
if (ctx != null) {
AlertDialog alertDialog = new AlertDialog.Builder(ctx)
.create();
alertDialog.setTitle(title);
alertDialog.setMessage(message);
alertDialog.setCancelable(false);
// setting OK Button
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
// activity.finish();
getFragmentManager().popBackStackImmediate();
}
});
alertDialog.show();
}
}
#Override
public void recyclerViewListClicked(View view, int position) {
ImageView button = (ImageView) view
.findViewById(R.id.imgbtn_favorite);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(ctx,
favorites.get(position));
Toast.makeText(
ctx,
ctx.getResources().getString(
R.string.add_favr),
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.star_colour);
} else {
sharedPreference.removeFavorite(ctx,
favorites.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.ic_action_name);
/* diseaseAdapter.remove(favorites
.get(position));*/
diseaseAdapter.remove(position);
Toast.makeText(
ctx,
ctx.getResources().getString(
R.string.remove_favr),
Toast.LENGTH_SHORT).show();
}
}
}
Adapter
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
/**
* Created by admin on 12/4/2017.
*/
public class DiseaseAdapter extends RecyclerView.Adapter<DiseaseAdapter.DiseaseAdapterViewHolder> {
List <String> data;
Context ctx;
private static RecyclerViewClickListener itemListener;
SharedPreference sharedPreference;
DiseaseAdapter(List <String> data, Context ctx, RecyclerViewClickListener itemListener){
this.data=data;
this.ctx=ctx;
sharedPreference = new SharedPreference();
this.itemListener = itemListener;
notifyDataSetChanged();
}
#Override
public DiseaseAdapterViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater=LayoutInflater.from(parent.getContext());
View view= inflater.inflate(R.layout.activity_listview,parent,false);
return new DiseaseAdapterViewHolder(view);
}
#Override
public void onBindViewHolder(DiseaseAdapterViewHolder holder, int position) {
final String title=data.get(position);
holder.textView1.setText(title);
if (checkFavoriteItem(title)) {
holder.imageButton.setImageResource(R.drawable.star_colour);
holder.imageButton.setTag("red");
} else {
holder.imageButton.setImageResource(R.drawable.ic_action_name);
holder.imageButton.setTag("grey");
}
}
#Override
public int getItemCount() {
return data.size();
}
class DiseaseAdapterViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView textView1;
ImageView imageButton;
public DiseaseAdapterViewHolder(View itemView) {
super(itemView);
textView1=(TextView) itemView.findViewById(R.id.textView);
imageButton=(ImageView)itemView.findViewById(R.id.imgbtn_favorite);
imageButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
notifyDataSetChanged();
itemListener.recyclerViewListClicked(v, this.getLayoutPosition());
}
}
/*Checks whether a particular product exists in SharedPreferences*/
public boolean checkFavoriteItem(String checkProduct) {
boolean check = false;
List<String> favorites = sharedPreference.getFavorites(ctx);
if (favorites != null) {
for (String product : favorites) {
if (product.equals(checkProduct)) {
check = true;
break;
}
}
}
return check;
}
public void add(String product) {
data.add(product);
notifyDataSetChanged();
}
public void remove(int position) {
data.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, data.size());
notifyDataSetChanged();
}
}
SharedPreference
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import com.google.gson.Gson;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SharedPreference {
public static final String PREFS_NAME = "PRODUCT_APP";
public static final String FAVORITES = "Product_Favorite";
public SharedPreference() {
super();
}
// This four methods are used for maintaining favorites.
public void saveFavorites(Context context, List<String> favorites) {
SharedPreferences settings;
Editor editor;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
editor = settings.edit();
Gson gson = new Gson();
String jsonFavorites = gson.toJson(favorites);
editor.putString(FAVORITES, jsonFavorites);
editor.commit();
}
public void addFavorite(Context context, String product) {
List<String> favorites = getFavorites(context);
if (favorites == null)
favorites = new ArrayList<String>();
favorites.add(product);
saveFavorites(context, favorites);
}
public void removeFavorite(Context context, String product) {
List<String> favorites = getFavorites(context);
if (favorites != null) {
favorites.remove(product);
saveFavorites(context, favorites);
}
}
public ArrayList<String> getFavorites(Context context) {
SharedPreferences settings;
List<String> favorites ;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
if (settings.contains(FAVORITES)) {
String jsonFavorites = settings.getString(FAVORITES, null);
Gson gson = new Gson();
String [] favoriteItems = (gson.fromJson(jsonFavorites,String [].class));
favorites = Arrays.asList(favoriteItems);
favorites = new ArrayList<String>(favorites);
} else
return null;
return (ArrayList<String>) favorites;
}
}
This is an error that i'm getting
FATAL EXCEPTION: main
Process: com.example.admin.fav, PID: 10974
java.lang.IndexOutOfBoundsException: Invalid index 3, size is 3
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
at com.example.admin.fav.Favourite.recyclerViewListClicked(Favourite.java:145)
at com.example.admin.fav.DiseaseAdapter$DiseaseAdapterViewHolder.onClick(DiseaseAdapter.java:90)
at android.view.View.performClick(View.java:5207)
at android.view.View$PerformClick.run(View.java:21168)
at android.os.Handler.handleCallback(Handler.java:746)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
Problem in your listener. You are using same adapter class for both MainActivity recylerview & Favourite activity recylerview. After you go back from favourite activity to Mainactivity still your listener read from Favourite activity. Thats the issue.
Solution
Create Static field to hold listener value here am created in SharedPreference Class:
public class SharedPreference {
public static final String PREFS_NAME = "PRODUCT_APP";
public static final String FAVORITES = "Product_Favorite";
/*Added*/
private static RecyclerViewClickListener listener;
public RecyclerViewClickListener getListener() {
return listener;
}
public void setListener(RecyclerViewClickListener listener) {
SharedPreference.listener = listener;
}
/*Added*/
...
}
Add this code to MainActivity & Favourite Activity 'OnCreate' method
sharedPreference.setListener(this);
public class MainActivity extends AppCompatActivity implements RecyclerViewClickListener{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreference.setListener(this);
....
}
public class Favourite extends AppCompatActivity implements RecyclerViewClickListener{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favourite);
sharedPreference.setListener(this);
....
}
Change Adapter 'OnClick method' to
#Override
public void onClick(View v) {
notifyDataSetChanged();
itemListener = sharedPreference.getListener();
itemListener.recyclerViewListClicked(v, this.getLayoutPosition());
}
And Finally change in MainActivity 'resume' method
#Override
protected void onResume() {
super.onResume();
sharedPreference.setListener(this);
da.notifyDataSetChanged();
}
Hope it helps.!
In your DiseaseAdapterViewHolder change the onclick methode to,
#Override
public void onClick(View v) {
itemListener.recyclerViewListClicked(v, this.getLayoutPosition());
notifyDataSetChanged();
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
i know it has been asked before for a different program but I am still getting error given below for my program
Thread [Thread-15956] (Suspended (exception ViewRootImpl$CalledFromWrongThreadException))
Please HELP!!
This is my MainActivity class
package a.example.na;
import java.util.Scanner;
import java.util.Set;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class MainActivity extends Activity {
private static TextView inputtext;
private BluetoothAdapter myBluetoothAdapter;
private Set<BluetoothDevice> pairedDevices;
private ListView myListView;
private ArrayAdapter<String> BTArrayAdapter;
private BluetoothDevice mDevice;
private Button findBtn;
private String address;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(myBluetoothAdapter == null) {
findBtn.setEnabled(false);
Toast.makeText(getApplicationContext(),"Your device does not support Bluetooth",
Toast.LENGTH_LONG).show();
} else {
inputtext = (TextView) findViewById(R.id.text);
findBtn = (Button)findViewById(R.id.search);
findBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
find(v);
}
});
myListView = (ListView)findViewById(R.id.listView1);
// create the arrayAdapter that contains the BTDevices, and set it to the ListView
BTArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
myListView.setAdapter(BTArrayAdapter);
myListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapterView, View v, int pos,
long arg3) {
// Add the name and address to an array adapter to show in a ListView
String i = (String) adapterView.getItemAtPosition(pos);
B b=new B(inputtext);
b.start();
Scanner scanner = new Scanner(i);
if(scanner.hasNextLine()) {
address =scanner.nextLine();
}
mDevice = myBluetoothAdapter.getRemoteDevice(address);
scanner.close();
}
});
}
}
final BroadcastReceiver bReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// add the name and the MAC address of the object to the arrayAdapter
BTArrayAdapter.add( device.getAddress()+ "\n" +device.getName() );
BTArrayAdapter.notifyDataSetChanged();
}
}
};
public void find(View view) {
if (myBluetoothAdapter.isDiscovering()) {
// the button is pressed when it discovers, so cancel the discovery
myBluetoothAdapter.cancelDiscovery();
}
else {
BTArrayAdapter.clear();
myBluetoothAdapter.startDiscovery();
registerReceiver(bReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
}
#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);
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregisterReceiver(bReceiver);
}
}
This is my separate Thread class
package com.bt;
import android.widget.TextView;
public class B extends Thread {
TextView inputtext;
public B(TextView x){
inputtext=x;
}
public void run(){
inputtext.setText("hero");
}
}
Your are touching the views(widgets) in the Non UI Thread.
public class B extends Thread {
TextView inputtext;
Activity activity;
public B(Activity activity, TextView x) {
inputtext = x;
this.activity = activity;
}
public void run() {
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
inputtext.setText("hero");
}
});
}
}
While starting the Thread
B b=new B(MainActivity.this, inputtext);
b.start();
This may turn out as a lame question, but I am a beginner and don't seem to understand the behavior of my app.
I have a SQLite data base, and a list view in the main activity.
In the list view I display the List no.(row id) and other details.
and on pressing the list item, a new activity opens up which displays the details in a textview and has 2 image buttons for delete and sync.
The app works just fine until I delete any entry.
Once I delete any entry the row id on the listview doesn't seem to update the row number. (if i delete the first row, the row on top shows 2(should be 1, as it is the new first row)).
However when I display the details of record it comes out correct. (the second item on the list show the row number 2)
Also when I press press an item in the list view whose position is same as the position i have deleted earlier the app crashes(Suppose i delete the first entry, after that whenever I click on the first Item on the list view to display it the app crashes)
Error I get on app crash :
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.aakashmaroti.fillup/com.example.aakashmaroti.fillup.DisplayDetails}: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
My main activity
package com.example.aakashmaroti.fillup;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class StartScreen extends ActionBarActivity implements View.OnClickListener {
FavoriteList favList = new FavoriteList();
TextView rid,ts,sd;
ListView lv;
Context context=this;
Find db=new Find(this);
List<FavoriteList> favoriteList;
LinearLayout layout;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start_screen);
Button b = (Button) findViewById(R.id.AddButton);
b.setOnClickListener(this);
lv = (ListView) findViewById(R.id.listview);
try
{
populateListViewFromDatabase();
} catch (Exception e)
{
Toast.makeText(getApplicationContext(), "Oops there has been an error "+e.toString()+"", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
showsDialog(position);
}
});
}
#Override
public void onResume()
{
super.onResume();
try
{
populateListViewFromDatabase();
} catch (Exception e)
{
Toast.makeText(getApplicationContext(), "Oops there has been an error "+e.toString()+"", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
#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_start_screen, 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);
}
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.AddButton:
startActivity(new Intent(this,Form.class));
break;
default: break;
}
}
public void populateListViewFromDatabase()throws Exception
{
Find info=new Find(this);
try
{
info.open();
SimpleCursorAdapter myCursorAdapter;
myCursorAdapter = info.listUp();
lv.setAdapter(myCursorAdapter);
info.close();
} catch (SQLException e)
{
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Oops there has been an error "+e.toString()+"", Toast.LENGTH_LONG).show();
}
}
public void showsDialog(int pos)
{
pos++;
String s = "";
s += pos;
Intent i = new Intent(getApplicationContext(), DisplayDetails.class);
i.putExtra("position", s);
startActivity(i);
try
{
populateListViewFromDatabase();
} catch (Exception e)
{
e.printStackTrace();
}
}
}
The sqlite data base managing class
package com.example.aakashmaroti.fillup;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Aakash Maroti on 28-Dec-14.
*/
public class Find
{
public static final String KEY_ROWID = "_id";
public static final String KEY_TIMESTAMP= "time_stamp";
public static final String KEY_IS_SYNCED = "sync";
public static final String KEY_NameOfCompany="name_of_company";
private static final String DATABASE_NAME = "FillUpFormsDB";
private static final String DATABASE_TABLE = "FillUpFormsTable";
private static final int DATABASE_VERSION = 1;
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static class DbHelper extends SQLiteOpenHelper
{
public DbHelper(Context context)
{
super(context,DATABASE_NAME,null,DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_IS_SYNCED +" TEXT NOT NULL, " +
KEY_TIMESTAMP +" TEXT NOT NULL, " +
KEY_NameOfCompany+" TEXT NOT NULL);"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
db.execSQL("DROP TABLE IF EXISTS "+DATABASE_TABLE);
onCreate(db);
}
}
public Find(Context c)
{
ourContext = c;
}
public Find open()throws SQLException
{
ourHelper = new DbHelper(ourContext);
ourDatabase=ourHelper.getWritableDatabase();
return this;
}
public void close()
{
ourHelper.close();
}
public long createEntry(String isSynced, String timeStamp, String nameOfCompany)
{
ContentValues cv=new ContentValues();
cv.put(KEY_IS_SYNCED,isSynced);
cv.put(KEY_TIMESTAMP,timeStamp);
cv.put(KEY_NameOfCompany,nameOfCompany);
return ourDatabase.insert(DATABASE_TABLE,null,cv);
}
public SimpleCursorAdapter listUp()
{
String columns[]=new String[]{KEY_ROWID,KEY_TIMESTAMP,KEY_IS_SYNCED};
Cursor c= ourDatabase.query(DATABASE_TABLE,columns,null,null,null,null,null);
int toViewIDs[] = new int[]{R.id.rowno,R.id.timestamp,R.id.syncdetails};
SimpleCursorAdapter CursorAdapter;
CursorAdapter = new SimpleCursorAdapter(ourContext,R.layout.design_row,c,columns,toViewIDs,0);
return CursorAdapter;
}
public String getDetails(long row)
{
String columns[]=new String[] {KEY_ROWID, KEY_IS_SYNCED, KEY_TIMESTAMP,KEY_NameOfCompany};
String result="";
Cursor c= ourDatabase.query(DATABASE_TABLE,columns,KEY_ROWID+"="+row,null,null,null,null);
if(c!=null)
{
String r;
c.moveToFirst();
r="\nRecord No. : "+c.getString(0)+"\n\nSync Status:"+c.getString(1)+"\n\nTime of Creation:\n"+c.getString(2)+"\n\nName of Company:\n"+c.getString(3);
return r;
}
return result;
}
public void DeleteRow(int pos)
{
ourDatabase.delete(DATABASE_TABLE,KEY_ROWID+"="+pos,null);
}
}
the class for the new activity that shows the result.
package com.example.aakashmaroti.fillup;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import java.sql.SQLException;
public class DisplayDetails extends ActionBarActivity implements View.OnClickListener
{
ImageButton ibSync;
ImageButton ibDelete;
TextView DispDetails;
int pos;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
String value="1";
if (extras != null) {
value = extras.getString("position");
}
pos=Integer.parseInt(value);
setContentView(R.layout.activity_display_details);
ibSync=(ImageButton)findViewById(R.id.imageButtonSync);
ibDelete=(ImageButton)findViewById(R.id.imageButtonDelete);
DispDetails = (TextView)findViewById(R.id.textViewDisplayDetails);
String s="";
ibSync.setOnClickListener(this);
ibDelete.setOnClickListener(this);
Find info1=new Find(this);
try
{
info1.open();
s=info1.getDetails(pos);
info1.close();
} catch (SQLException e)
{
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Oops there has been an error "+e.toString()+"", Toast.LENGTH_LONG).show();
}
DispDetails.setText(s);
}
#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_display_details, 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);
}
#Override
public void onClick(View v)
{
if(v.getId()==R.id.imageButtonSync)
{
Toast.makeText(getApplicationContext(), "This functionality has not yet been added", Toast.LENGTH_LONG).show();
}
if(v.getId()==R.id.imageButtonDelete)
{ Find info1=new Find(this);
try
{
info1.open();
info1.DeleteRow(pos);
info1.close();
} catch (SQLException e)
{
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Oops there has been an error "+e.toString()+"", Toast.LENGTH_LONG).show();
}
Toast.makeText(getApplicationContext(), "This record has been successfully deleted", Toast.LENGTH_LONG).show();
cancel();
}
}
public void cancel()
{
this.finish();
return;
}
}
Xml file of a single row in the listview
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="50dp"
android:text=""
android:textStyle="bold"
android:clickable="true"
android:id="#+id/rowno"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="50dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text=""
android:clickable="true"
android:id="#+id/timestamp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="50dp"
android:textStyle="bold"
android:text=""
android:clickable="true"
android:id="#+id/syncdetails"/>
</LinearLayout>
Any help will be greatly appreciated.
Thanks in advance.
Its because you are passing the list view item position, it should be the database row id.
Change
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
showsDialog(position);
}
to
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
TextView pos = (TextView) view.findViewById(R.id.rowno);
showsDialog(pos.getText().toString());
}
Also you said
Once I delete any entry the row id on the listview doesn't seem to update the row number. (if i delete the first row, the row on top shows 2(should be 1, as it is the new first row)).
But it wouldn't because this is the database row id not the list view position.
You only fetch your Cursor in onResume or onCreate. So your Cursor remains same although Data changes. Look into LoaderManager Class.
In the android app I am creating, I have a scrollable tabs from my TabsPagerAdapter class which extends FragmentPagerAdapter. However, in my app, I am trying to display all user installed apps on the phone into a section of a tab. However the class which was able to return all of that extended FragmentActivity.
I tried to follow this, but it is not working.
How to list all downloaded android apps in a fragment
Sadly, after much research I found out that I can only put fragments in different tabs and only have one Activity displayed at any one time and the tabs themselves can only return Fragments.
I really need to put all the user installed apps into a Fragment in this case I guess but I am unsure how to implement this...I have an Adapter class and everything.
Here is my InstalledAppActivity class which extends FragmentActivity to return all user downloaded apps.
package com.spicycurryman.getdisciplined10.app;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
import com.javatechig.listapps.ApplicationAdapter;
import java.util.ArrayList;
import java.util.List;
public class InstalledAppActivity extends FragmentActivity {
private PackageManager packageManager = null;
private List<ApplicationInfo> applist = null;
private ApplicationAdapter listadaptor = null;
ListView InstalledAppList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.installed_apps);
InstalledAppList = (ListView) findViewById(R.id.Installed_List);
packageManager = getPackageManager();
new LoadApplications().execute();
InstalledAppList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
ApplicationInfo app = applist.get(i);
try {
Intent intent = packageManager
.getLaunchIntentForPackage(app.packageName);
if (null != intent) {
startActivity(intent);
}
} catch (ActivityNotFoundException e) {
Toast.makeText(InstalledAppActivity.this, e.getMessage(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(InstalledAppActivity.this, e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
});
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
packageManager = getPackageManager();
new LoadApplications().execute();
return inflater.inflate(R.layout.installed_apps, container, false);
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.block, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
boolean result = true;
switch (item.getItemId()) {
case R.id.main_text: {
displayAboutDialog();
break;
}
default: {
result = super.onOptionsItemSelected(item);
break;
}
}
return result;
}
private void displayAboutDialog() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.app_name));
builder.setMessage(getString(R.string.slogan));
builder.setPositiveButton("Know More", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://javatechig.com"));
startActivity(browserIntent);
dialog.cancel();
}
});
builder.setNegativeButton("No Thanks!", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder.show();
}
private AdapterView.OnItemClickListener OnItemClickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
}
protected void onListItemClick(ListView InstalledAppList, View v, int position, long id) {
ApplicationInfo app = applist.get(position);
try {
Intent intent = packageManager
.getLaunchIntentForPackage(app.packageName);
if (null != intent) {
startActivity(intent);
}
} catch (ActivityNotFoundException e) {
Toast.makeText(InstalledAppActivity.this, e.getMessage(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(InstalledAppActivity.this, e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
};
private List<ApplicationInfo> checkForLaunchIntent(List<ApplicationInfo> list) {
ArrayList<ApplicationInfo> applist = new ArrayList<ApplicationInfo>();
for (ApplicationInfo info : list) {
try {
if (null != packageManager.getLaunchIntentForPackage(info.packageName)) {
applist.add(info);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return applist;
}
private class LoadApplications extends AsyncTask<Void, Void, Void> {
private ProgressDialog progress = null;
#Override
protected Void doInBackground(Void... params) {
applist = checkForLaunchIntent(packageManager.getInstalledApplications(PackageManager.GET_META_DATA));
listadaptor = new ApplicationAdapter(InstalledAppActivity.this,
R.layout.snippet_list_row, applist);
return null;
}
#Override
protected void onCancelled() {
super.onCancelled();
}
#Override
protected void onPostExecute(Void result) {
//setListAdapter(listadaptor);
InstalledAppList.setAdapter(listadaptor);
super.onPostExecute(result);
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
}
Here is an example of how you would do it:
package com.spicycurryman.getdisciplined10.app;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageItemInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
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.ListView;
import com.ibc.android.demo.appslist.app.ApkAdapter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class InstalledAppActivity extends Fragment
implements OnItemClickListener {
//hi
PackageManager packageManager;
ListView apkList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setHasOptionsMenu(true);
View rootView = inflater.inflate(R.layout.user_installed, container, false);
packageManager = getActivity().getPackageManager();
/*To filter out System apps*/
apkList = (ListView) rootView.findViewById(R.id.applist);
new LoadApplications(getActivity().getApplicationContext()).execute();
return rootView;
}
/**
* Return whether the given PackageInfo represents a system package or not.
* User-installed packages (Market or otherwise) should not be denoted as
* system packages.
*
* #param pkgInfo
* #return boolean
*/
private boolean isSystemPackage(PackageInfo pkgInfo) {
return ((pkgInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) ? true
: false;
}
private boolean isSystemPackage1(PackageInfo pkgInfo) {
return ((pkgInfo.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) ? false
: true;
}
// Don't need in Fragment
/*#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.block, menu);
// super.onCreateOptionsMenu(menu,inflater);
}*/
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//ApkAdapter apkAdapter=(ApkAdapter)apkList.getAdapter();
}
private class LoadApplications extends AsyncTask<Void, Void, Void> {
Context mContext;
private ProgressDialog pDialog;
List<PackageInfo> packageList1 = new ArrayList<PackageInfo>();
public LoadApplications(Context context){
Context mContext = context;
}
#Override
protected Void doInBackground(Void... params) {
List<PackageInfo> packageList = packageManager
.getInstalledPackages(PackageManager.GET_PERMISSIONS);
/* List<ApplicationInfo> list = mContext.getPackageManager().getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES);
for(int n = 0;n<list.size();n++){
if ((list.get(n).flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP))
}*/
for(PackageInfo pi : packageList) {
boolean b = isSystemPackage(pi);
boolean c = isSystemPackage1(pi);
if(!b || !c ) {
packageList1.add(pi);
}
}
//sort by application name
final PackageItemInfo.DisplayNameComparator comparator = new PackageItemInfo.DisplayNameComparator(packageManager);
Collections.sort(packageList1, new Comparator<PackageInfo>() {
#Override
public int compare(PackageInfo lhs, PackageInfo rhs) {
return comparator.compare(lhs.applicationInfo, rhs.applicationInfo);
}
});
return null;
}
#Override
protected void onCancelled() {
super.onCancelled();
}
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(InstalledAppActivity.this.getActivity());
pDialog.setMessage("Loading your apps...");
pDialog.show();
}
#Override
protected void onPostExecute(Void result) {
apkList.setAdapter(new ApkAdapter(getActivity(), packageList1, packageManager));
if (pDialog.isShowing()){
pDialog.dismiss();
}
super.onPostExecute(result);
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
}
way don't you just from youre main activity on click off the tab create a fragment with a listview in it and displays the data list there?? you can pars the list to the fragment bay saying
fragmentclass fragment = new fragmentclass(list);
fragment.show();
if youre having truble understanding fragments you can watch this great tutorial on it especialy the part on inter fragment communication is realy use full
I've built a splash screen that loads a (splash) activity and then starts another activity and it works fine. (I've attached it below - it's called SPLASH 1)
I created another splash screen to replace this one which is supposed to only run once - then after creating a SharedPreferences boolean it is supposed to load another activity. Everything seems fine with this but now when it loads the new activity, none of the menuitems appear. I have no idea what changed in SPLASH 2 - but something in there is causing the MenuItems not to appear after it loads the exact same activity SPLASH 1 does (NEWCORE.JAVA)
I'm really not sure what is going on here - any help is greatly appreciated!
(please let me know if any additional info is needed)
SPLASH 1. (WORKING)
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.content.Intent;
import com.nfc.linkingmanager.R;
public class SplashScreen extends Activity {
private boolean mIsBackButtonPressed;
private static final int SPLASH_DURATION = 1000;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
Handler handler = new Handler();
// run a thread after 2 seconds to start the home screen
handler.postDelayed(new Runnable() {
#Override
public void run() {
// make sure we close the splash screen so the user won't come back when it presses back key
finish();
if (!mIsBackButtonPressed) {
// start the home screen if the back button wasn't pressed already
Intent intent = new Intent(SplashScreen.this, NewCore.class);
SplashScreen.this.startActivity(intent);
}
}
}, SPLASH_DURATION); // time in milliseconds (1 second = 1000 milliseconds) until the run() method will be called
}
#Override
public void onBackPressed() {
// set the flag to true so the next activity won't start up
mIsBackButtonPressed = true;
super.onBackPressed();
}
}
SPLASH 2 (NOT WORKING - CAUSES MENUITEMS not to appear on the activity it loads)
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.content.Intent;
import com.nfc.linkingmanager.R;
import android.content.SharedPreferences;
import java.lang.Object;
import android.preference.PreferenceManager;
public class SplashScreen extends Activity
{
private Handler handler = new Handler()
{
public void handleMessage(Message msg)
{
Intent i = new Intent(SplashScreen.this, AppActivity.class);
SplashScreen.this.startActivity(i);
this.finish();
}
};
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if(!prefs.getBoolean("first_time", false))
{
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("first_time", true);
editor.commit();
Intent i = new Intent(SplashScreen.this, NewCore.class);
this.startActivity(i);
this.finish();
}
else
{
this.setContentView(R.layout.country_list);
handler.sendEmptyMessageDelayed(0, 2000);
}
}
}
NEWCORE.JAVA (Connected to by both Splash Screens - Only missing MenuItems when using SPLASH 2)
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.AdapterView.OnItemClickListener;
public class NewCore extends ListActivity {
public static final String ROW_ID = "row_id";
private ListView conListView;
private CursorAdapter conAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
conListView=getListView();
conListView.setOnItemClickListener(viewConListener);
// map each name to a TextView
String[] from = new String[] { "name" };
int[] to = new int[] { R.id.countryTextView };
conAdapter = new SimpleCursorAdapter(NewCore.this, R.layout.country_list, null, from, to);
setListAdapter(conAdapter); // set adapter
}
#Override
protected void onResume()
{
super.onResume();
new GetContacts().execute((Object[]) null);
}
#Override
protected void onStop()
{
Cursor cursor = conAdapter.getCursor();
if (cursor != null)
cursor.deactivate();
conAdapter.changeCursor(null);
super.onStop();
}
private class GetContacts extends AsyncTask<Object, Object, Cursor>
{
DatabaseConnector dbConnector = new DatabaseConnector(NewCore.this);
#Override
protected Cursor doInBackground(Object... params)
{
dbConnector.open();
return dbConnector.getAllContacts();
}
#Override
protected void onPostExecute(Cursor result)
{
conAdapter.changeCursor(result); // set the adapter's Cursor
dbConnector.close();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.country_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
Intent addContact = new Intent(NewCore.this, NewCore.class);
startActivity(addContact);
return super.onOptionsItemSelected(item);
}
OnItemClickListener viewConListener = new OnItemClickListener()
{
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3)
{
Intent viewCon = new Intent(NewCore.this, NewCore.class);
viewCon.putExtra(ROW_ID, arg3);
startActivity(viewCon);
}
};
}
Create a new activity which extends the Android Activity class, and place your menu handling in there. Then, extend the new activity in your other activities - thus ensuring that the menu handling is consistent. For lists, you could create a second new activity which extends ListActivity, or grab the ListActivity code and just make that extend your previous activity with the menus.
In Splash 2 put
SetContentView(R.layout.country_list);
just below
super.onCreate(savedInstanceState);