Showing multiple tables from sqlDatabase - android

I am developing an app quote and I am using a local database to import the quotes.
This is the 4 tables made in sqldatabase.
enter image description here
and in here cobined
Table Database
my table name is "be.db"
i put in the asset folder in android studio
as you can see in the picture the title "Life" has more than 1 quote thats
because in the app when i want to click the item "life" i want it to show me the first quote then i slide to another quote here is front of the app
front page of app
the problem i dont know how to import multiple or 3 tables from sqldatabase i only know how to import one as you can see below this my code in my class "DatabaseHelper" in android studio:
public class DataBaseHelper extends SQLiteOpenHelper {
public static final String DBNAME="be.db";
public static final String DBLOCATION=Environment.getDataDirectory()+"/data/com.example.z210.story/databases/";
private Context mcontext;
private SQLiteDatabase mDatabase;
public DataBaseHelper(Context context) {
super(context,DBNAME,null,1);
this.mcontext=context;
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void openDatabase() {
//l'acces au notre base de donnees
String dbPath=mcontext.getDatabasePath(DBNAME).getPath();
if(mDatabase!=null && mDatabase.isOpen()){
return;
}
mDatabase=SQLiteDatabase.openDatabase(dbPath,null,SQLiteDatabase.OPEN_READWRITE);
}
public void closeDatabbase(){
if(mDatabase !=null){
mDatabase.close();
}
}
public ArrayList getAllTitles(){
ArrayList arrayList=new ArrayList();
openDatabase();
Cursor res=mDatabase.rawQuery("select * from title ",null);
res.moveToFirst();
while(!res.isAfterLast()){
arrayList.add(res.getString(res.getColumnIndex("title")));
res.moveToNext();
}
res.close();
closeDatabbase();
return arrayList;
}
public ArrayList getAllQuotes(){
ArrayList arrayList=new ArrayList();
openDatabase();
Cursor res=mDatabase.rawQuery("select * from quote ",null);
res.moveToFirst();
while(!res.isAfterLast()){
arrayList.add(res.getString(res.getColumnIndex("quote")));
res.moveToNext();
}
res.close();
closeDatabbase();
return arrayList;
}
public String get_full_story(String title){
String full_story;
openDatabase();
Cursor res =mDatabase.rawQuery("select * from title where quote like '"+getAllQuotes() +"'",null);
res.moveToFirst();
full_story=res.getString(res.getColumnIndex("quote"));
res.close();
closeDatabbase();
return full_story;
}
}
and here is my code in the main activity
public class MainActivity extends AppCompatActivity {
DataBaseHelper db =new DataBaseHelper (this);
private DrawerLayout mDrawerLayout;
TextView textViewSub,textView3;
Typeface tf1,tf2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView=(ListView)findViewById(R.id.list);
File database=getApplicationContext().getDatabasePath(db.DBNAME);
if(false==database.exists()) {
db.getDatabaseName();
if (copyDatabase(this)) {
} else {
return;
}
}
ArrayList listTitles=db.getAllTitles();
ArrayList listTitle=db.getAllQuotes();
ArrayAdapter arrayAdapter=new ArrayAdapter(this,R.layout.row_itm,R.id.textView3,listTitles);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String az=String.valueOf(parent.getItemAtPosition(position));
Intent intent=new Intent(MainActivity.this,ShowActivity.class);
intent.putExtra("p",az);
startActivity(intent);
}
});
mDrawerLayout = findViewById(R.id.drawer);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
mDrawerLayout.closeDrawers();
return true;
}
});
mDrawerLayout.addDrawerListener(
new DrawerLayout.DrawerListener() {
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
}
#Override
public void onDrawerOpened(View drawerView) {
}
#Override
public void onDrawerClosed(View drawerView) {
}
#Override
public void onDrawerStateChanged(int newState) {
}
}
);
textViewSub=(TextView)findViewById(R.id.textViewSub);
textView3=(TextView)findViewById(R.id.textView3);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionbar = getSupportActionBar();
actionbar.setDisplayHomeAsUpEnabled(true);
actionbar.setHomeAsUpIndicator(R.drawable.para);
final String[] itm=getResources().getStringArray(R.array.index);
(this,R.layout.row_itm,R.id.textView3,itm);
tf1=Typeface.createFromAsset(getAssets(),"orangeblossoms.ttf");
textViewSub.setTypeface(tf1);
}
private boolean copyDatabase(Context context) {
try {
InputStream inputStream=context.getAssets().open(db.DBNAME);
String outFileName=db.DBLOCATION+db.DBNAME;
OutputStream outputStream=new FileOutputStream(outFileName);
byte[] buff=new byte[1024];
int lenght=0;
while ((lenght=inputStream.read(buff))>0){
outputStream.write(buff,0,lenght);
}
outputStream.flush();
outputStream.close();
return true;
} catch (Exception e) {
return false;
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
public void error(View view) {
finish();
}
public void favo(View view) {
}
}

Sir,
It should be using array of String or class/object to retrieve the result instead of string only.
Your SQL call return the result set cursor instead of String. Conceptually wrong .

Related

How to save user drawings to SQLite database in another activity?

I have a class extends View and I do my drawings there.I open another activity from menu after I finished my drawing. In second activity, there is editText field for username and there is also a save button. I want to make them saved to my SQLite database, first drawing and then the image related to user. How can I do that ? Now this is my code currently and I'm getting an error.
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context com.example.mydrawingapp.View.AppView.getContext()' on a null object reference
at com.example.mydrawingapp.SecondActivity$1.onClick(SecondActivity.java:31)
My Database Helper class:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "drawingApp.db";
public static final String TABLE_NAME="saveUser";
public static final String COL_1 = "ID";
public static final String COL_2="username";
public static final String COL_3="image";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null,1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE saveUser (ID INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT,image BLOB)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(" DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public long addImage(String user, byte[] image){
SQLiteDatabase database = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("username",user);
contentValues.put("image",image);
long res = database.insert("saveUser",null,contentValues);
database.close();
return res;
}
}
This is the code that I have in my Second Activity class:
public class SecondActivity extends AppCompatActivity {
private EditText textUsername;
private Button buttonRegister;
private String username;
private AppView appView;
private DatabaseHelper dbHelper;
private byte[] image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
textUsername = (EditText) findViewById(R.id.editText);
username = textUsername.getText().toString();
buttonRegister=(Button) findViewById(R.id.saveButton);
buttonRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
appView= new AppView(appView.getContext(),null );
image = appView.saveImage();
dbHelper.addImage(username,image);
}
});
}
}
Main Activity:
public class MainActivity extends AppCompatActivity {
private AppView appView;
private AlertDialog.Builder currentAlertDialog;
private ImageView widthImageView;
private AlertDialog dialogLineWidth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
appView = findViewById(R.id.view);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.clearId:
appView.clear();
break;
case R.id.saveId:
openLoginDialog();
break;
case R.id.lineWidth:
showLineWidthDialog();
break;
}
return super.onOptionsItemSelected(item);
}
private void openLoginDialog() {
Intent intent = new Intent(this,SecondActivity.class);
startActivity(intent);
}
void showLineWidthDialog() {
currentAlertDialog = new AlertDialog.Builder(this);
View view = getLayoutInflater().inflate(R.layout.width_dialog, null);
final SeekBar widthSeekBar = view.findViewById(R.id.widthSeekBar);
Button setLineWidthButton = view.findViewById(R.id.widthDialogButton);
widthImageView = view.findViewById(R.id.imageViewId);
setLineWidthButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
appView.setLineWidth(widthSeekBar.getProgress());
dialogLineWidth.dismiss();
currentAlertDialog = null;
}
});
widthSeekBar.setOnSeekBarChangeListener(widthSeekBarChange);
currentAlertDialog.setView(view);
dialogLineWidth = currentAlertDialog.create();
dialogLineWidth.setTitle("Set Line Width");
dialogLineWidth.show();
}
SeekBar.OnSeekBarChangeListener widthSeekBarChange = new SeekBar.OnSeekBarChangeListener() {
Bitmap bitmap = Bitmap.createBitmap(400, 100, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
Paint p = new Paint();
p.setColor(appView.getDrawingColor());
p.setStrokeCap(Paint.Cap.ROUND);
p.setStrokeWidth(progress);
bitmap.eraseColor(Color.WHITE);
canvas.drawLine(30, 50, 370, 50, p);
widthImageView.setImageBitmap(bitmap);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
};
}
your context is null so you need initialize that in this way:
public class SecondActivity extends AppCompatActivity {
private EditText textUsername;
private Button buttonRegister;
private String username;
private AppView appView;
private DatabaseHelper dbHelper;
private byte[] image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
textUsername = (EditText) findViewById(R.id.editText);
username = textUsername.getText().toString();
buttonRegister=(Button) findViewById(R.id.saveButton);
buttonRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
appView= new AppView(SecondActivity.this ,null ); // change this line
image = appView.saveImage();
dbHelper.addImage(username,image);
}
});
}
buttonRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
appView= new AppView(**appView**.getContext(),null );
image = appView.saveImage();
dbHelper.addImage(username,image);
}
appView<-- this is null at the point of click initialize this first

UI not populating ListView with items saved in SQLite Database

I've been facing issues with my MoviesApp for a while now and I feel that I've exhausted all my knowledge on this; I am quite new with Android so bear with me :-)
MoviesApp is a simple movie listing app, in which the user can scroll through the list of films, see details for each one and save their favorites in an SQLite DB.
I use SharedPreference to sort movies based by popularity, rating and favorites (the only list saved in the database), but when I change through each one, the UI is not updating at all.
I am really stuck and honestly, I could do with another pair of eyes, because, even if the answer is staring me in the face, I wouldn't be able to see it 😫😫😫
I pasted the link to the project below:
https://drive.google.com/file/d/1SweLpwfo5RntXrbtLPP3N_xS1bVs32Ze/view?usp=sharing
Thank you!!
Update: I believe the problem would in the MainActivity class, where the RecyclerView Loader is declared - specifically in onLoadFinished().
#SuppressWarnings({"WeakerAccess", "unused", "CanBeFinal"})
public class MainActivity extends AppCompatActivity implements
LoaderManager.LoaderCallbacks,
MovieAdapter.MovieDetailClickHandler, SwipeRefreshLayout.OnRefreshListener {
private static final String TAG = MainActivity.class.getSimpleName();
public static final String MOVIE_ID = "movieId";
private final static String LIFECYCLE_CALLBACKS_LAYOUT_MANAGER_KEY = "KeyForLayoutManagerState";
Parcelable savedLayoutManagerState;
public RecyclerView movieListRV;
private GridLayoutManager gridLayoutManager =
new GridLayoutManager(this, 1);
Context context = this;
// Loader IDs for loading the main API and the poster API, respectively
private static final int ID_LOADER_LIST_MOVIES = 1;
private static final int ID_LOADER_CURSOR = 2;
// adapter
private MovieAdapter adapter;
// detect internet connection
NetworkDetection networkDetection;
// swipe to refresh
SwipeRefreshLayout swipeRefreshLayout;
// sortOption
String sortOption = null;
// movie projection
private final String[] projection = new String[]{
MoviesContract.MovieEntry.COLUMN_MOVIE_POSTER,
MoviesContract.MovieEntry.COLUMN_MOVIE_ID
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Stetho.initializeWithDefaults(this);
Toolbar toolbar = findViewById(R.id.settings_activity_toolbar);
setSupportActionBar(toolbar);
toolbar.setTitleTextColor(Color.WHITE);
networkDetection = new NetworkDetection(this);
swipeRefreshLayout = findViewById(R.id.discover_swipe_refresh);
swipeRefreshLayout.setOnRefreshListener(MainActivity.this);
swipeRefreshLayout.setColorScheme(android.R.color.holo_red_dark);
movieListRV = findViewById(R.id.recycler_view_movies);
movieListRV.setLayoutManager(gridLayoutManager);
movieListRV.setHasFixedSize(true);
ViewTreeObserver viewTreeObserver = movieListRV.getViewTreeObserver();
viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
calculateSize();
}
});
adapter = new MovieAdapter(this, this);
movieListRV.setAdapter(adapter);
RecyclerViewItemDecorator itemDecorator = new RecyclerViewItemDecorator(context,
R.dimen.item_offset);
movieListRV.addItemDecoration(itemDecorator);
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences
(context);
SharedPreferences.OnSharedPreferenceChangeListener preferenceChangeListener = new
SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
adapter.deleteItemsInList();
onRefresh();
if (key.equals(getString(R.string.pref_sort_by_key))) {
initializeloader();
}
}
};
preferences.registerOnSharedPreferenceChangeListener(preferenceChangeListener);
initializeloader();
}
private static final int sColumnWidth = 200;
private void calculateSize() {
int spanCount = (int) Math.floor(movieListRV.getWidth() / convertDPToPixels(sColumnWidth));
((GridLayoutManager) movieListRV.getLayoutManager()).setSpanCount(spanCount);
}
#SuppressWarnings("SameParameterValue")
private float convertDPToPixels(int dp) {
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
float logicalDensity = metrics.density;
return dp * logicalDensity;
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable(LIFECYCLE_CALLBACKS_LAYOUT_MANAGER_KEY, gridLayoutManager
.onSaveInstanceState());
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
if (savedInstanceState != null) {
savedLayoutManagerState = savedInstanceState.getParcelable
(LIFECYCLE_CALLBACKS_LAYOUT_MANAGER_KEY);
movieListRV.getLayoutManager().onRestoreInstanceState(savedLayoutManagerState);
}
}
#Override
public Loader onCreateLoader(int id, Bundle args) {
adapter.deleteItemsInList();
String urlMovieActivity;
switch (id) {
case ID_LOADER_CURSOR:
return new CursorLoader(context, MoviesContract.MovieEntry.MOVIES_CONTENT_URI,
projection, null, null, null);
case ID_LOADER_LIST_MOVIES:
urlMovieActivity = NetworkUtils.buildUrlMovieActivity(context, sortOption);
return new MovieLoader(this, urlMovieActivity);
default:
return null;
}
}
#Override
public void onLoadFinished(Loader loader, Object data) {
adapter.deleteItemsInList();
TextView noMoviesMessage = findViewById(R.id.no_movies_found_tv);
switch (loader.getId()) {
case ID_LOADER_CURSOR:
adapter.InsertList(data);
break;
case ID_LOADER_LIST_MOVIES:
//noinspection unchecked
List<MovieItem> movieItems = (List<MovieItem>) data;
if (networkDetection.isConnected()) {
noMoviesMessage.setVisibility(View.GONE);
adapter.InsertList(movieItems);
movieListRV.getLayoutManager().onRestoreInstanceState(savedLayoutManagerState);
} else {
noMoviesMessage.setVisibility(View.VISIBLE);
}
break;
}
adapter.notifyDataSetChanged();
}
#Override
public void onLoaderReset(Loader loader) {
switch (loader.getId()) {
case ID_LOADER_CURSOR:
adapter.InsertList(null);
break;
case ID_LOADER_LIST_MOVIES:
adapter.InsertList(null);
break;
}
}
#Override
public void onPostResume(Loader loader) {
super.onPostResume();
getLoaderManager().initLoader(ID_LOADER_CURSOR, null, this);
}
#Override
public void onSelectedItem(int movieId) {
Intent goToDetailActivity = new Intent(this, DetailMovieActivity.class);
goToDetailActivity.putExtra(MOVIE_ID, movieId);
startActivity(goToDetailActivity);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_general, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
int id = menuItem.getItemId();
if (id == R.id.action_general_settings) {
Intent goToSetting = new Intent(this, SettingsActivity.class);
startActivity(goToSetting);
return true;
} else if (id == R.id.action_refresh) {
onRefresh();
}
return super.onOptionsItemSelected(menuItem);
}
/**
* Called when a swipe gesture triggers a refresh.
*/
#Override
public void onRefresh() {
adapter.deleteItemsInList();
swipeRefreshLayout.setRefreshing(false);
restartloader();
adapter.notifyDataSetChanged();
}
private void restartloader() {
adapter.deleteItemsInList();
if (MoviePreferences.getSortByPreference(context).equals(getString(R.string
.pref_sort_by_favourite))) {
getLoaderManager().restartLoader(ID_LOADER_CURSOR, null, MainActivity
.this);
}
if (MoviePreferences.getSortByPreference(context).equals(getString(R.string
.pref_sort_by_popularity))) {
sortOption = NetworkUtils.MOST_POPULAR_PARAM;
getLoaderManager().restartLoader(ID_LOADER_LIST_MOVIES, null,
MainActivity.this);
}
if (MoviePreferences.getSortByPreference(context).equals(getString(R.string
.pref_sort_by_rating))) {
sortOption = NetworkUtils.TOP_RATED_PARAM;
getLoaderManager().restartLoader(ID_LOADER_LIST_MOVIES, null,
MainActivity.this);
}
adapter.notifyDataSetChanged();
}
public void initializeloader() {
restartloader();
if (MoviePreferences.getSortByPreference(context).equals(getString(R.string
.pref_sort_by_favourite))) {
getLoaderManager().initLoader(ID_LOADER_CURSOR, null, MainActivity
.this);
}
if (MoviePreferences.getSortByPreference(context).equals(getString(R.string
.pref_sort_by_popularity))) {
onRefresh();
sortOption = NetworkUtils.MOST_POPULAR_PARAM;
getLoaderManager().initLoader(ID_LOADER_LIST_MOVIES, null,
MainActivity.this);
}
if (MoviePreferences.getSortByPreference(context).equals(getString(R.string
.pref_sort_by_rating))) {
onRefresh();
sortOption = NetworkUtils.TOP_RATED_PARAM;
getLoaderManager().initLoader(ID_LOADER_LIST_MOVIES, null,
MainActivity.this);
}
adapter.notifyDataSetChanged();
}
}

Display black blank screen while showing folderwisw all photo from gallery

Hi I developed one app where I want to display folder wise all photos from storage. I implemented the code for it but the problem is that when activity is created it display black blank screen for 5 sec and then display all folder.
Here is my code:
public class ImageWithFolder extends AppCompatActivity implements AdapterView.OnItemClickListener {
List<GridViewItem> gridItems = new ArrayList<GridViewItem>();
String redirect;
GridView gridView;
Bitmap bitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_imagefolder);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar1);
setSupportActionBar(toolbar);
final ActionBar ab = getSupportActionBar();
assert ab != null;
ab.setDisplayHomeAsUpEnabled(true);
Intent ii = getIntent();
redirect = ii.getStringExtra("next_activity");
gridView = (GridView) findViewById(R.id.gridView);
setGridAdapter();
}
private void setGridAdapter() {
createGridItems(Environment.getExternalStorageDirectory().getAbsolutePath());
MyGridAdapter adapter = new MyGridAdapter(this, gridItems);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(this);
}
private void createGridItems(String directoryPath) {
File[] files = new File(directoryPath).listFiles(new ImageFileFilter());
for (File file : files) {
if (file.isDirectory()) {
if (file.listFiles((new DirFilter())).length > 0) {
createGridItems(file.getAbsolutePath());
}
if (file.listFiles((new ImageFilter())).length > 0) {
gridItems.add(new GridViewItem(file.getAbsolutePath(), true, null));
}
}
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home: {
finish();
}
return true;
}
return super.onOptionsItemSelected(item);
}
private boolean isImageFile(String filePath) {
if (filePath.endsWith(".jpg") || filePath.endsWith(".png") || filePath.endsWith(".jpeg")) {
return true;
}
return false;
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (redirect.equalsIgnoreCase("1")) {
Intent ii = new Intent(ImageWithFolder.this, SelectPhotos.class);
ii.putExtra("path", gridItems.get(i).getPath());
startActivity(ii);
} else if (redirect.equalsIgnoreCase("2")) {
Intent ii = new Intent(ImageWithFolder.this, AlbumSelectPhotos.class);
ii.putExtra("path", gridItems.get(i).getPath());
startActivity(ii);
}
}
private class ImageFileFilter implements FileFilter {
#Override
public boolean accept(File file) {
if (file.isDirectory()) {
return true;
} else if (isImageFile(file.getAbsolutePath())) {
return true;
}
return false;
}
}
private class ImageFilter implements FileFilter {
#Override
public boolean accept(File file) {
if (isImageFile(file.getAbsolutePath())) {
return true;
}
return false;
}
}
private class DirFilter implements FileFilter {
#Override
public boolean accept(File file) {
if (file.isDirectory()) {
return true;
}
return false;
}
}
}
I am not getting what is going wrong with the code.
Can anyone give solution regarding black screen appear at the first time.
Thanks in advance.
Put your read file method in async..
Call Aysnc:
new LoadData().execute()
public class LoadData extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
createGridItems(Environment.getExternalStorageDirectory().getAbsolutePath());
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
MyGridAdapter adapter = new MyGridAdapter(this, gridItems);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(this);
}
}
If you are comfortable with RxJava then use Observal, This is the best soluton.

android initialize two times in two different activities

Not able to initialize parse two times in two another activity to call data from two classes of parse and put them in different list views. at second time when opening contact activity by action item then the app stops
Main Activity.java
public class MainActivity extends ActionBarActivity {
private CountryAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Parse.initialize(this, "0FgKGokshcBPQSpY**********", "f1hZ9W4c***********");
ParseObject.registerSubclass(Country.class);
mAdapter = new CountryAdapter(this, new ArrayList<Country>());
ListView mListView = (ListView) findViewById(R.id.country_list);
mListView.setAdapter(mAdapter);
updateData();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_contact) {
Intent i = new Intent(this, ContactActivity.class);
startActivity(i);
return true;
}
return super.onOptionsItemSelected(item);
}
public void updateData() {
ParseQuery<Country> query = ParseQuery.getQuery(Country.class);
query.setCachePolicy(ParseQuery.CachePolicy.CACHE_THEN_NETWORK);
query.findInBackground(new FindCallback<Country>() {
#Override
public void done(List<Country> countrys, com.parse.ParseException e) {
if (countrys != null) {
mAdapter.clear();
for (int i = 0; i < countrys.size(); i++) {
mAdapter.add(countrys.get(i));
}
}
}
});
}
}
ContactActivity.java
public class ContactActivity extends ActionBarActivity {
private ContactAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact);
Parse.initialize(this, "0FgKGoksh********************", "f1hZ9W4cKO2Ag*******************");
ParseObject.registerSubclass(Contact.class);
mAdapter = new ContactAdapter(this, new ArrayList<Contact>());
ListView mListView = (ListView) findViewById(R.id.contact_list);
mListView.setAdapter(mAdapter);
updateData();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_contact, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
public void updateData() {
ParseQuery<Contact> query = ParseQuery.getQuery(Contact.class);
query.setCachePolicy(ParseQuery.CachePolicy.CACHE_THEN_NETWORK);
query.findInBackground(new FindCallback<Contact>() {
#Override
public void done(List<Contact> contact, com.parse.ParseException e) {
if (contact != null) {
mAdapter.clear();
for (int i = 0; i < contact.size(); i++) {
mAdapter.add(contact.get(i));
}
}
}
});
}
}
You should initialize parse in a class which extends Application class like this
public class MyApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
Parse.initialize(this, "xxxxxxxxxxxx", "xxxxxxxxx");
}
}
and put application class name in manifest file like
<application
android:name=".MyApplication" />

Calling method in second activity

I'm writing a tip app where the user selects a check, and then on the second activity the subtotal is displayed. However, I'm completely lost on how I display my subtotal. I have a getSubtotal() method but I don't know how to call it.
First Activity
public class TableListActivity extends Activity {
private ListView mListView;
private TableListAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_table_list);
// Find the ListView, create an adapter that reads our list of checks,
// and connect the two
mListView = (ListView)findViewById(R.id.listView);
mAdapter = new TableListAdapter(this, DataStore.CHECKS);
mListView.setAdapter(mAdapter);
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Intent intent = new Intent (TableListActivity.this, PayCheckActivity.class);
intent.putExtra(PayCheckActivity.Extra_check, arg2);
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.table_list, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_refresh) {
// TODO do stuff here
Toast.makeText(this, "Refresh", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}}
Second Activity
public class PayCheckActivity extends Activity{
String Thank;
Button Sign;
Button fifteen;
Button eighteen;
Button twenty;
String sample;
public static final String Extra_check= "abc";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.paycheck);
Sign = (Button)findViewById(R.id.Sign);
fifteen= (Button)findViewById(R.id.fifteen);
eighteen= (Button)findViewById(R.id.eighteen);
twenty= (Button)findViewById(R.id.twenty);
Sign.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Toast msg = Toast.makeText(getBaseContext(),"Thank You", Toast.LENGTH_LONG);
msg.show();
}});
fifteen.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Toast msg = Toast.makeText(getBaseContext(),"Thank Yolllllu", Toast.LENGTH_LONG);
msg.show();
}});}}
Check.java
public class Check {
private long id;
private String tableName;
private ArrayList<MenuItem> mItems = new ArrayList<MenuItem>();
private boolean hasBeenSigned = false;
public static class MenuItem {
public String name;
public Amount cost;
public MenuItem(String itemDescription, double cost) {
this.name = itemDescription;
this.cost = new Amount(cost);
}
}
public Check(long id, String tableName) {
this.id = id;
this.tableName = tableName;
}
public long getId() {
return id;
}
#Override
public String toString() {
// The ArrayAdapter uses toString to get the text to display in the list item
// We override toString here to display the table name
return tableName;
}
public void addItem(String itemDescription, double cost) {
mItems.add(new MenuItem(itemDescription, cost));
}
public String getTableName() {
return tableName;
}
public Amount getSubtotal() {
double total = 0;
for (MenuItem item : mItems) {
total += item.cost.getRawValue();
}
return new Amount(total);
}
public void markAsSigned() {
hasBeenSigned = true;
}
public int getItemCount() {
return mItems.size();
}
public MenuItem getMenuItemAt(int index) {
return mItems.get(index);
}}
Just a quick hint: You are sending some data to the second activity via Intent (onItemClick). In the second activity in onCreate, you can pick this data and call your getSubtotal method. Since it's not quite clear, what "Check" does, it's up to you how to instantiate it:
public class PayCheckActivity extends Activity{
// ...
protected void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
if(intent != null) {
String value = intent.getStringExtra(PayCheckActivity.Extra_check);
Check check = .....
check.getSubtotal()
}
}
// ...
}

Categories

Resources