let's get straight. I want to build an movie app which have popular and kid, when data's liked, it store in SQLite. So in layout favorited, i make 2 layout, popular and kid. To distribute the data, i used clause category : movie and genre_ids : 16 / not. But when i test my app (previously i reinstall it, like suggestion in this site) and liked the movie, in logcat show something like this :
2019-10-11 09:24:05.941 5582-5582/com.example.apkfin5 E/SQLiteDatabase: Error inserting overview=blablabla. backdroppath=/n6bUvigpRFqSwmPp1m2YADdbRBc.jpg release_date=2019-10-02 [genre_ids]=null posterpath=/udDclJoHjfjb8Ekgsd4FDteOkCU.jpg id=475557 title=Joker category=movie
android.database.sqlite.SQLiteConstraintException: NOT NULL constraint failed: favorite.genre_ids (code 1299 SQLITE_CONSTRAINT_NOTNULL)
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:796)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1564)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1433)
at com.example.apkfin5.db.FavHelper.insert(FavHelper.java:58)
at com.example.apkfin5.provider.FavProvider.insert(FavProvider.java:69)
at android.content.ContentProvider$Transport.insert(ContentProvider.java:266)
at android.content.ContentResolver.insert(ContentResolver.java:1603)
at com.example.apkfin5.ui.activity.DetailFilmActivity.onOptionsItemSelected(DetailFilmActivity.java:170)
at android.app.Activity.onMenuItemSelected(Activity.java:3608)
You can see that the genre_ids is null, and i set my app, when data's null, data will not distribute to SQLite. So why i can't get the genre_ids ?
For support the diagnose, here's my dbHelper :
public class DbHelper extends SQLiteOpenHelper {
private static String DATABASE_NAME = "dbmovieapp";
private static final int DATABASE_VER = 1;
private static final String SQL_CREATE_FAVORITE = String.format(
"CREATE TABLE %s" + " (%s INTEGER PRIMARY KEY AUTOINCREMENT," +
" %s TEXT NOT NULL, " +
" %s TEXT NOT NULL, " +
" %s TEXT NOT NULL, " +
" %s TEXT NOT NULL, " +
" %s TEXT NOT NULL, " +
" %s TEXT NOT NULL, " +
" %s TEXT NOT NULL, " +
" %s NULL)",
TABLE_FAVORITE,
DbContract.Columns._ID,
DbContract.Columns.FAVID,
DbContract.Columns.BACKDROPPATH,
DbContract.Columns.POSTERPATH,
DbContract.Columns.TITLE,
DbContract.Columns.RELEASE_DATE,
DbContract.Columns.OVERVIEW,
DbContract.Columns.CATEGORY,
DbContract.Columns.GENRE
);
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VER);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(SQL_CREATE_FAVORITE);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITE);
onCreate(sqLiteDatabase);
}
}
my favorite Helper :
public class FavHelper {
private static final String DATABASE_TABLE = TABLE_FAVORITE;
private static DbHelper dbHelper;
private static FavHelper INSTANCE;
private static SQLiteDatabase database;
public FavHelper(Context context) {dbHelper = new DbHelper(context);}
public static FavHelper getInstance(Context context) {
if(INSTANCE == null) {synchronized (SQLiteOpenHelper.class){
if(INSTANCE == null) {INSTANCE = new FavHelper(context);}
}}
return INSTANCE;
}
public void open() throws SQLException {database = dbHelper.getWritableDatabase();}
public void close() {dbHelper.close();
if (database.isOpen())
database.close();
}
public Cursor queryById(String id) {
return database.query(DATABASE_TABLE,null,_ID + " = ?"
,new String[]{id}, null, null, null, null);}
public Cursor query() {
return database.query(DATABASE_TABLE, null,null,null,null,null,_ID + " DESC");}
public long insert(ContentValues contentValues) {return database.insert(DATABASE_TABLE,null,contentValues); }
public int update(String id, ContentValues contentValues) {return database.update(DATABASE_TABLE,contentValues,_ID + " = ?", new String[] {id});}
public int delete(String id) {return database.delete(DATABASE_TABLE, _ID + " = ?", new String[]{id});}
public static ArrayList<Favorite> getFilmFavorite(Cursor cursor) {
ArrayList<Favorite> arrayList = new ArrayList<>();
while (cursor.moveToNext()) {
int id = cursor.getInt(cursor.getColumnIndexOrThrow(_ID));
int favId = cursor.getInt(cursor.getColumnIndexOrThrow(FAVID));
String backdrop = cursor.getString(cursor.getColumnIndexOrThrow(BACKDROPPATH));
String posterpath = cursor.getString(cursor.getColumnIndexOrThrow(POSTERPATH));
String title = cursor.getString(cursor.getColumnIndexOrThrow(TITLE));
String overview = cursor.getString(cursor.getColumnIndexOrThrow(OVERVIEW));
String release = cursor.getString(cursor.getColumnIndexOrThrow(RELEASE_DATE));
String category = cursor.getString(cursor.getColumnIndexOrThrow(CATEGORY));
List genre = Collections.singletonList(cursor.getString(cursor.getColumnIndexOrThrow(String.valueOf(GENRE))));
if(!genre.equals("16") && category.equals("movie")) {
arrayList.add(new Favorite(id, favId, title, backdrop, posterpath, overview, release, category, genre));
}}
return arrayList;
}
public static ArrayList<Favorite> getFilmKidFavorite(Cursor cursor) {
ArrayList<Favorite> arrayList = new ArrayList<>();
while (cursor.moveToNext()) {
int id = cursor.getInt(cursor.getColumnIndexOrThrow(_ID));
int favId = cursor.getInt(cursor.getColumnIndexOrThrow(FAVID));
String backdrop = cursor.getString(cursor.getColumnIndexOrThrow(BACKDROPPATH));
String posterpath = cursor.getString(cursor.getColumnIndexOrThrow(POSTERPATH));
String title = cursor.getString(cursor.getColumnIndexOrThrow(TITLE));
String overview = cursor.getString(cursor.getColumnIndexOrThrow(OVERVIEW));
String release = cursor.getString(cursor.getColumnIndexOrThrow(RELEASE_DATE));
String category = cursor.getString(cursor.getColumnIndexOrThrow(CATEGORY));
List genre = Collections.singletonList(cursor.getString(cursor.getColumnIndexOrThrow(String.valueOf(GENRE))));
if(genre.equals("16") && category.equals("movie")) {
arrayList.add(new Favorite(id, favId, title, backdrop, posterpath, overview, release, category, genre));
}
}
return arrayList;
}
my dbContract :
public class DbContract {
private static String SCHEME = "content";
public static String AUTHORITY = "com.example.apkfin5";
public static final class Columns implements BaseColumns {
public static String TABLE_FAVORITE = "favorite";
public static String FAVID = "id";
public static String BACKDROPPATH = "backdroppath";
public static String POSTERPATH = "posterpath";
public static String TITLE = "title";
public static String OVERVIEW = "overview";
public static String RELEASE_DATE = "release_date";
public static String CATEGORY = "category";
public static List GENRE = Collections.singletonList("genre_ids");
public static Uri C_URI = new Uri.Builder().scheme(SCHEME).authority(AUTHORITY)
.appendPath(TABLE_FAVORITE).build();
}
public static String getColumnString(Cursor cursor, String column) {return cursor.getString(cursor.getColumnIndex(column));}
public static int getColumnInt(Cursor cursor, String column) {return cursor.getInt(cursor.getColumnIndex(column));}
}
a half of my detail movie when it's being like and store it in Favorite model :
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if(cekFav()) {
Uri uri = Uri.parse(C_URI + "/" + id);
getContentResolver().delete(uri,null,null);
item.setIcon(R.drawable.ic_favorite_border_24dp);
Toast.makeText(this,getString(R.string.unFav), Toast.LENGTH_LONG).show();}
else {
favorite.setId(Favid);
favorite.setTitle(tittle);
favorite.setPosterPath(poster);
favorite.setBackdropPath(backdrop);
favorite.setReleasedate(releasedate);
favorite.setOverView(overView);
favorite.setGenre(Collections.singletonList(genre));
favorite.setCategoty("movie");
ContentValues contentValues = new ContentValues();
contentValues.put(FAVID,Favid);
contentValues.put(TITLE,tittle);
contentValues.put(OVERVIEW,overView);
contentValues.put(BACKDROPPATH,backdrop);
contentValues.put(RELEASE_DATE,releasedate);
contentValues.put(POSTERPATH,poster);
contentValues.put(String.valueOf(GENRE), genre);
contentValues.put(CATEGORY,"movie");
if (getContentResolver().insert(C_URI,contentValues) != null) {
Toast.makeText(this,tittle + " " + getString(R.string.Fav), Toast.LENGTH_LONG).show();
item.setIcon(R.drawable.ic_favorite);
} else { Toast.makeText(this, tittle + " " + getString(R.string.favError), Toast.LENGTH_LONG).show();}
}
sendRefreshBroadcast(getApplicationContext());
return super.onOptionsItemSelected(item);
}
Model of movie to Store data from Api :
public class Film {
#SerializedName("id")
#Expose
private int id;
#SerializedName("backdrop_path")
#Expose
private String backdrop;
#SerializedName("title")
#Expose
private String title;
#SerializedName("poster_path")
#Expose
private String posterPath;
#SerializedName("release_date")
#Expose
private String releaseDate;
#SerializedName("vote_average")
#Expose
private float rating;
#SerializedName("genre_ids")
#Expose
private List<Integer> genreIds;
#SerializedName("overview")
#Expose
private String overView;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getBackdrop() {return backdrop;}
public void setBackdrop(String backdrop) {this.backdrop = backdrop;}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getPosterPath() {
return posterPath;
}
public void setPosterPath(String posterPath) {
this.posterPath = posterPath;
}
public String getReleaseDate() {
return releaseDate;
}
public void setReleaseDate(String releaseDate) {
this.releaseDate = releaseDate;
}
public float getRating() {
return rating;
}
public void setRating(float rating) {
this.rating = rating;
}
public List<Integer> getGenreIds() {
return genreIds;
}
public void setGenreIds(List<Integer> genreIds) {
this.genreIds = genreIds;
}
public String getOverView() {return overView;}
public void setOverView(String overView) {this.overView = overView;}
}
Then Favorite Model, to storage data when's like :
public class Favorite implements Parcelable {
private int id;
private int mId;
private String backdropPath;
private String posterPath;
private String title;
private String overview;
private String releasedate;
private String category;
private List genre;
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public int getmId() { return mId; }
public void setmId(int mId) { this.mId = mId; }
public String getBackdropPath() {
return backdropPath;
}
public void setBackdropPath(String backdropPath) {
this.backdropPath = backdropPath;
}
public String getPosterPath() {
return posterPath;
}
public void setPosterPath(String posterPath) {
this.posterPath = posterPath;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getOverView() {
return overview;
}
public void setOverView(String overview) {
this.overview = overview;
}
public String getReleasedate() { return releasedate; }
public void setReleasedate(String releasedate) { this.releasedate = releasedate; }
public String getCategory() {return category;}
public void setCategoty(String categoty) {
this.category = categoty;
}
public List getGenre() {return genre;}
public void setGenre(List genre) {this.genre = genre;}
public Favorite() {
}
public Favorite(int id, int mId, String title, String backdrop, String posterpath, String overview, String release, String category, List genre) {
this.id = id;
this.mId = mId;
this.backdropPath = backdrop;
this.posterPath = posterpath;
this.overview = overview;
this.title = title;
this.releasedate = release;
this.category = category;
this.genre = genre;
}
protected Favorite(Parcel in) {
id = in.readInt();
mId = in.readInt();
backdropPath = in.readString();
posterPath = in.readString();
title = in.readString();
overview = in.readString();
releasedate = in.readString();
category = in.readString();
if (in.readByte() == 0x01) {
genre = new ArrayList<>();
in.readList(genre, Parcelable.class.getClassLoader());
} else {
genre = null;
}
}
public Favorite(Cursor cursor) {
this.id = getColumnInt(cursor,_ID);
this.mId = getColumnInt(cursor,FAVID);
this.title = getColumnString(cursor,TITLE);
this.category = getColumnString(cursor,CATEGORY);
this.posterPath = getColumnString(cursor,POSTERPATH);
this.overview = getColumnString(cursor, OVERVIEW);
this.backdropPath = getColumnString(cursor, BACKDROPPATH);
this.genre = Collections.singletonList(getColumnString(cursor, String.valueOf(GENRE)));
}
public static final Creator<Favorite> CREATOR = new Creator<Favorite>() {
#Override
public Favorite createFromParcel(Parcel in) {
return new Favorite(in);
}
#Override
public Favorite[] newArray(int size) {
return new Favorite[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeInt(id);
parcel.writeInt(mId);
parcel.writeString(backdropPath);
parcel.writeString(posterPath);
parcel.writeString(title);
parcel.writeString(overview);
parcel.writeString(releasedate);
parcel.writeString(category);
if (genre == null) {
parcel.writeByte((byte) (0x00));
} else {
parcel.writeByte((byte) (0x01));
parcel.writeList(genre);
}
}
}
This's my first time assigment to build with two different view from 1 API. So ya, i got a little confused here. Thank for the answer.
i've been realized that i need to deserialized this list : genre_id, so guys, can you tell me how to deserialized "genre_ids": [
99,
10402
]
is it use Class List, then the value just Public int id ? or i need more id ? cause some genre_ids have more than one int.
So, i try to solve with deserialized, but i didn't understand how to implement with that data to the database.
And the best i can do was make another database for save data when it clicked. Before that, i build another request from the web so i can get data only from kid. Make sure that the other request didn't get data, set the request with "without_genres", i'm using tmdb btw. That need because you don't want duplicate kid's datas from reguler movie and kid show in tab favorite. Furthermore, i used that database to make widget. So you don't want your 2 widget (reguler and kid) have similiar movie kid in both of it.
Related
I'm trying to get the data from the arrayBundlePack after getting data from enqueue call, I'm trying to use BufferedWriter to the saved data in the arrayBundlePack & write in the txt file, but it just won't get the output I wanted.
I'm not sure if that's the way to output an arrayList model class.
Here's the code
private ArrayList<BundlePack> arrayBundlePack;
Call<BundlePackRepo> call = .............. // api content
call.enqueue(new Callback<BundlePackRepo>() {
#Override
public void onResponse(Call<BundlePackRepo> call, retrofit2.Response<BundlePackRepo> response) {
if (response.isSuccessful()) {
BundlePackRepo repos = response.body();
BundlePackRepo.bundlepacks[] bundlePacksarray;
bundlePacksarray = repos.getBundlePacks();
BundlePack bundlePack;
for (int a = 0; a < bundlePacksarray.length; a++) {
bundlePack = new BundlePack();
bundlePack.setPromotion_kit(bundlePacksarray[a].getPromotion_kit());
bundlePack.setStock_code(bundlePacksarray[a].getStock_code());
bundlePack.setIssue_ref(bundlePacksarray[a].getIssue_ref());
bundlePack.setQuantity(bundlePacksarray[a].getQuantity());
String sysMod = bundlePacksarray[a].getSys_mod();
String modifyDate = bundlePacksarray[a].getModify_dt();
try {
bundlePack.setSys_mod(df.parse(sysMod));
bundlePack.setModify_dt(df.parse(modifyDate));
} catch (java.text.ParseException e) {
e.printStackTrace();
}
bundlePack.setStatus(bundlePacksarray[a].getStatus());
arrayBundlePack.add(bundlePack);
//Trying to put out the data to text file
String filename = "bundlepack.txt";
File txtData = new File(getApplicationContext().getFilesDir(), filename);
FileWriter txtWriter = null;
try {
txtWriter = new FileWriter(txtData);
BufferedWriter fileWriter = new BufferedWriter(txtWriter);
for (BundlePack bdpack : arrayBundlePack) {
fileWriter.write(bdpack.toString());
fileWriter.newLine();
fileWriter.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
BundlePack
#Entity
public class BundlePack{
#PrimaryKey(autoGenerate = true)
private int id;
#ColumnInfo(name = "promotion_kit")
private String promotion_kit;
#ColumnInfo(name = "stock_code")
private String stock_code;
#ColumnInfo(name = "issue_ref")
private String issue_ref;
#ColumnInfo(name = "quantity")
private Integer quantity;
#TypeConverters(DateConverter.class)
#ColumnInfo(name = "sys_mod")
private Date sys_mod;
#TypeConverters(DateConverter.class)
#ColumnInfo(name = "modify_dt")
private Date modify_dt;
#ColumnInfo(name = "status")
private String status;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPromotion_kit() {
return promotion_kit;
}
public void setPromotion_kit(String promotion_kit) {
this.promotion_kit = promotion_kit;
}
public String getStock_code() {
return stock_code;
}
public void setStock_code(String stock_code) {
this.stock_code = stock_code;
}
public String getIssue_ref() {
return issue_ref;
}
public void setIssue_ref(String issue_ref) {
this.issue_ref = issue_ref;
}
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
public Date getSys_mod() {
return sys_mod;
}
public void setSys_mod(Date sys_mod) {
this.sys_mod = sys_mod;
}
public Date getModify_dt() {
return modify_dt;
}
public void setModify_dt(Date modify_dt) {
this.modify_dt = modify_dt;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
#Override
public String toString() {
return "BundlePack{" +
"id=" + id +
", promotion_kit='" + promotion_kit + '\'' +
", stock_code='" + stock_code + '\'' +
", issue_ref='" + issue_ref + '\'' +
", quantity=" + quantity +
", sys_mod=" + sys_mod +
", modify_dt=" + modify_dt +
", status='" + status + '\'' +
'}';
}
}
BundlePackRepo
public class BundlePackRepo {
private String count;
private bundlepacks[] bundlepacks;
public String getCount() {
return count;
}
public void setCount(String count) {
this.count = count;
}
public bundlepacks[] getBundlePacks() {
return bundlepacks;
}
public void setBundlePacks(bundlepacks[] bundlePacks) {
this.bundlepacks = bundlePacks;
}
public static class bundlepacks {
#SerializedName("promotionkit")
private String promotion_kit;
#SerializedName("stock_code")
private String stock_code;
#SerializedName("iss_ref")
private String issue_ref;
#SerializedName("qty")
private int quantity;
#SerializedName("sys_mod")
private String sys_mod;
#SerializedName("modify_dt")
private String modify_dt;
#SerializedName("status")
private String status;
#SerializedName("id")
private String id;
public String getPromotion_kit() {
return promotion_kit;
}
public void setPromotion_kit(String promotion_kit) {
this.promotion_kit = promotion_kit;
}
public String getStock_code() {
return stock_code;
}
public void setStock_code(String stock_code) {
this.stock_code = stock_code;
}
public String getIssue_ref() {
return issue_ref;
}
public void setIssue_ref(String issue_ref) {
this.issue_ref = issue_ref;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public String getSys_mod() {
return sys_mod;
}
public void setSys_mod(String sys_mod) {
this.sys_mod = sys_mod;
}
public String getModify_dt() {
return modify_dt;
}
public void setModify_dt(String modify_dt) {
this.modify_dt = modify_dt;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
}
You are calling toString() to convert each bundlepack instance to a string for output. So you need to an override for toString to the bundlepack class. It needs to format the instance in the form that you need for your purposes.
Since you currently haven't overridden that method, your code is currently calling Object.toString() ... which only outputs the object's class name and hashcode.
Your IDE may well have a helper to generate a toString for a class, based on the fields of the class.
public class MovieController extends Controller {
public static List<Movie> movies;
static {
movies = new ArrayList<>();
movies.add(new Movie(1, "dsfnejhf", "Movie on Racing", "abcd", "xyz"));
movies.add(new Movie(2, "F2", "Comedy Movie", "Venkatesh", "Tamanna"));
movies.add(new Movie(3, "Titanic", "Movie", "Hero", "Heroine"));
movies.add(new Movie(4, "Saaho", "action", "Prabhas", "Shradda kapoor"));
movies.add(new Movie(5, "Bhahubali 1", "action", "Prabhas", "Tamanna"));
}
public Result insert(Http.Request request) {
JsonNode jsonNode = request.body().asJson();
if (jsonNode == null) {
return badRequest("insufficient movie information");
}
Movie movie = Json.fromJson(jsonNode, Movie.class);
movies.add(movie);
return ok(Json.toJson(movie));
}
this is Movie class and above MovieController class now how to write code for increment of id value from existing id number
public class Movie {
private int id;
private String movieName;
private String description;
private String hero;
private String heroine;
public Movie(int id, String movieName, String description, String hero, String heroine) {
this.id = id;
this.movieName = movieName;
this.description = description;
this.hero = hero;
this.heroine = heroine;
}
public Result getMoviesById(int id) {
Movie movie = findById(id);
if (movie == null) {
return notFound("movie not found");
}
return ok(Json.toJson(movie));
}
Just get the maximum id from the movies list (0 for a empty list) and increase this with 1
int maxId = movies.stream()
.mapToInt(m -> m.getId())
.max()
.orElse(0);
int nextId = maxId + 1;
an example with a mimimal MovieController:
import java.util.ArrayList;
import java.util.List;
public class MovieController {
public static List<Movie> movies;
static {
movies = new ArrayList<>();
movies.add(new Movie(1, "dsfnejhf", "Movie on Racing", "abcd", "xyz"));
movies.add(new Movie(2, "F2", "Comedy Movie", "Venkatesh", "Tamanna"));
movies.add(new Movie(3, "Titanic", "Movie", "Hero", "Heroine"));
movies.add(new Movie(4, "Saaho", "action", "Prabhas", "Shradda kapoor"));
movies.add(new Movie(5, "Bhahubali 1", "action", "Prabhas", "Tamanna"));
}
public Movie insert(Movie movie) {
int maxId = movies.stream()
.mapToInt(m -> m.getId())
.max()
.orElse(0);
movie.setId(++maxId);
movies.add(movie);
return movie;
}
public static void main(String[] args) {
MovieController mc = new MovieController() ;
System.out.println("start---");
for (Movie m : movies) {
System.out.println(m);
}
Movie newMovie = new Movie(-1,"aa","bb", "h1", "h2");
newMovie = mc.insert(newMovie);
System.out.println("after insert---");
for (Movie m : movies) {
System.out.println(m);
}
}
}
and a minimal Movie:
public class Movie {
private int id;
private String movieName;
private String description;
private String hero;
private String heroine;
public Movie(int id, String movieName, String description, String hero, String heroine) {
this.id = id;
this.movieName = movieName;
this.description = description;
this.hero = hero;
this.heroine = heroine;
}
public Movie getMoviesById(int id) {
Movie movie = findById(id);
if (movie == null) {
return null;
}
return movie;
}
private Movie findById(int id) {
return null;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Override
public String toString() {
return "Movie{" +
"id=" + id +
", movieName='" + movieName + '\'' +
", description='" + description + '\'' +
", hero='" + hero + '\'' +
", heroine='" + heroine + '\'' +
'}';
}
}
It will add a movie to the list with id 6.
public void alphabeticalListing()
{
BufferedReader br = null;
List<String> lineList = new ArrayList<String>();
try
{
br = new BufferedReader(new FileReader(wishlistname + ".txt"));
String line;
while((line = br.readLine())!=null)
{
lineList.add(line);
}
Collections.sort(lineList);
for(String output : lineList) {
System.out.println(output);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
The file Contains Movie Details...
Example:
MovieName:DirectorName:ProducerName:Rating:Review
Terminator: Arfath: Khalid : 8 : VeryGood
Hangover : John : Lucas : 7 : NotBad
Jumanji : Rock : Brock : 9 : Good
I want to select ProducerName Column and do SOP in alphabetically like,
Output:
Brock
Khalid
Lucas
You can use java Compartor for sorting by creating Movie as model class. You can achieve this using below code:
public static void readDataFromFile(String filePath) throws FileNotFoundException
{
List<Movie> movies = new ArrayList<Movie>();
File file = new File(filePath);
Scanner sc = new Scanner(file);
while (sc.hasNextLine())
{
String txtLine = sc.nextLine();
//Extract data from single from txt file row
String[] data = txtLine.split(":");
Movie movie = new Movie(data[0], data[1], data[2], data[3], data[4]);
//Add to movies list
movies.add(movie);
}
System.out.println("Unsorted-----------");
System.out.println(movies);
System.out.println("Sorting by director-----------");
Collections.sort(movies, new DirectorSorter());
System.out.println(movies);
System.out.println("Sorting by producer-----------");
Collections.sort(movies, new ProducerSorter());
System.out.println(movies);
}
public static class Movie
{
private String name;
private String director;
private String producer;
private String rating;
private String review;
public Movie(){}
public Movie(String name, String director, String producer, String rating, String review){
this.name = name;
this.director = director;
this.producer = producer;
this.rating = rating;
this.review = review;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
public String getProducer() {
return producer;
}
public void setProducer(String producer) {
this.producer = producer;
}
public String getRating() {
return rating;
}
public void setRating(String rating) {
this.rating = rating;
}
public String getReview() {
return review;
}
public void setReview(String review) {
this.review = review;
}
#Override
public String toString() {
return "Movie : " + name + " - " + director + " - " + producer + " - " + rating + " - " + review + "\n";
}
}
public static class DirectorSorter implements Comparator<Movie>{
#Override
public int compare(Movie o1, Movie o2) {
return o1.getDirector().compareTo(o2.getDirector());
}
}
public static class ProducerSorter implements Comparator<Movie>{
#Override
public int compare(Movie o1, Movie o2) {
return o1.getProducer().compareTo(o2.getProducer());
}
}
I'm trying to deal with this baking JSON:
in android app so this is the class to bring the JSON data from link:
OpenBakingJsonUtils.java:
public final class OpenBakingJsonUtils {
public static ArrayList<ArraysLists> getSimpleBakingStringsFromJson(Context context, String bakingJsonString)
throws JSONException {
final String ID = "id";
final String NAME = "name";
final String SERVINGS = "servings";
final String INGREDIENTS = "ingredients";
final String STEPS = "steps";
final String QUANTITY = "quantity";
final String MEASURE = "measure";
final String INGREDIENT = "ingredient";
final String IDSTEPS = "id";
final String SHORTDESCRIPTION = "shortDescription";
final String DESCRIPTION = "description";
final String VIDEOURL = "videoURL";
final String THUMBNAILURL = "thumbnailURL";
ArrayList<ArraysLists> parsedRecipeData = new ArrayList<ArraysLists>();
ArrayList<BakingItem> Baking = new ArrayList<BakingItem>();
JSONArray recipeArray = new JSONArray(bakingJsonString);
for (int i = 0; i < recipeArray.length(); i++) {
int id;
String name;
int servings;
double quantity;
String measure;
String ingredient;
int idSteps;
String shortDescription;
String description;
String videoURL;
String thumbnailURL;
JSONObject recipeObject = recipeArray.getJSONObject(i);
id = recipeObject.getInt(ID);
name = recipeObject.getString(NAME);
servings = recipeObject.getInt(SERVINGS);
ArrayList<IngredientsItem> Ingredients = new ArrayList<IngredientsItem>();
JSONArray ingredientsArray = recipeObject.getJSONArray(INGREDIENTS);
for(int j = 0 ; j< ingredientsArray.length(); j++) {
JSONObject ingredientsObject = ingredientsArray.getJSONObject(j);
quantity = ingredientsObject.getDouble(QUANTITY);
measure = ingredientsObject.getString(MEASURE);
ingredient = ingredientsObject.getString(INGREDIENT);
Ingredients.add(new IngredientsItem(quantity, measure, ingredient));
}
ArrayList<StepsItem> Steps = new ArrayList<StepsItem>();
JSONArray stepsArray = recipeObject.getJSONArray(STEPS);
for(int j = 0 ; j< stepsArray.length(); j++) {
JSONObject stepsObject = stepsArray.getJSONObject(j);
idSteps = recipeObject.getInt(IDSTEPS);
shortDescription = stepsObject.getString(SHORTDESCRIPTION);
description = stepsObject.getString(DESCRIPTION);
videoURL = stepsObject.getString(VIDEOURL);
thumbnailURL = stepsObject.getString(THUMBNAILURL);
Steps.add(new StepsItem(idSteps, shortDescription, description, videoURL, thumbnailURL));
}
Baking.add(new BakingItem(id, name, servings, Ingredients, Steps));
parsedRecipeData.add(new ArraysLists(Baking, Ingredients, Steps));
}
return parsedRecipeData;
}
}
as you see there are 3 ArrayList classes:
ArrayList<BakingItem>
ArrayList<IngredientsItem>
ArrayList<StepsItem>
and this is the code for each one:
BakingItem.java:
public class BakingItem implements Parcelable {
private int id;
private String name;
private int servings;
private ArrayList<IngredientsItem> ingredients = new ArrayList<IngredientsItem>();
private ArrayList<StepsItem> steps = new ArrayList<StepsItem>();
public BakingItem(int id, String name, int servings, ArrayList<IngredientsItem> ingredients, ArrayList<StepsItem> steps) {
this.id = id;
this.name = name;
this.servings = servings;
this.ingredients = ingredients;
this.steps = steps;
}
#Override
public void writeToParcel(Parcel out, int flags) {
out.writeInt(id);
out.writeString(name);
out.writeInt(servings);
out.writeTypedList(ingredients);
out.writeTypedList(steps);
}
private BakingItem(Parcel in) {
this.id = in.readInt();
this.name = in.readString();
this.servings = in.readInt();
ingredients = new ArrayList<IngredientsItem>();
in.readTypedList(ingredients, IngredientsItem.CREATOR);
}
public BakingItem() {
}
#Override
public int describeContents() {
return 0;
}
public static final Parcelable.Creator<BakingItem> CREATOR = new Parcelable.Creator<BakingItem>() {
#Override
public BakingItem createFromParcel(Parcel in) {
return new BakingItem(in);
}
#Override
public BakingItem[] newArray(int i) {
return new BakingItem[i];
}
};
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getServings() {
return servings;
}
}
IngredientsItem.java:
public class IngredientsItem implements Parcelable {
private double quantity;
private String measure;
private String ingredient;
public IngredientsItem(double quantity, String measure, String ingredient) {
this.quantity = quantity;
this.measure = measure;
this.ingredient = ingredient;
}
#Override
public void writeToParcel(Parcel out, int flags) {
out.writeDouble(quantity);
out.writeString(measure);
out.writeString(ingredient);
}
private IngredientsItem(Parcel in) {
this.quantity = in.readDouble();
this.measure = in.readString();
this.ingredient = in.readString();
}
public IngredientsItem() {
}
#Override
public int describeContents() {
return 0;
}
public static final Parcelable.Creator<IngredientsItem> CREATOR = new Parcelable.Creator<IngredientsItem>() {
#Override
public IngredientsItem createFromParcel(Parcel in) {
return new IngredientsItem(in);
}
#Override
public IngredientsItem[] newArray(int i) {
return new IngredientsItem[i];
}
};
public double getQuantity() {
return quantity;
}
public String getMeasure() {
return measure;
}
public String getIngredient() {
return ingredient;
}
}
as well as the StepsItem class
and the forth is the ArraysLists.java which contain all the 3 arrays above and returned by the OpenBakingJsonUtils.java:
Then I'm trying to call these JSON data in different activities
so in MainActivity.java in loadInBackground:
Override
public ArrayList<BakingItem> loadInBackground() {
URL recipeRequestUrl = NetworkUtils.buildUrl();
try {
String jsonBakingResponse = NetworkUtils.getResponseFromHttpUrl(recipeRequestUrl);
ArrayList<ArraysLists> simpleJsonBakingData = OpenBakingJsonUtils.getSimpleBakingStringsFromJson(MainActivity.this, jsonBakingResponse);
return simpleJsonBakingData;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
I call the returned ArrayList from OpenBakingJsonUtils.java which is in this case the ArraysLists,
then in DetailActivity.java in doInBackground:
#Override
protected ArrayList<ArraysLists> doInBackground(Object... params) {
if (params.length == 0) {
return null;
}
URL reviewsRequestUrl = NetworkUtils.buildUrl();
try {
String jsonReviewResponse = NetworkUtils.getResponseFromHttpUrl(reviewsRequestUrl);
ArrayList<ArraysLists> simpleJsonReviewData = OpenBakingJsonUtils.getSimpleBakingStringsFromJson(DetailsActivity.this, jsonReviewResponse);
return simpleJsonReviewData;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
here I call the ArrayList of ArraysLists too but the problem in adapters of MainActivity.java and DetailsActivity.java in onBindViewHolder:
holder.CommentContent.setText(String.valueOf(mCommentsItems.get(position).getQuantity()));
it just says that cannot resolve method getQuantity() which is in IngredientsItem.java while I used the ArraysLists.java that returned by OpenBakingJsonUtils.java
so what should I do to call methods from BakingItem.java and IngredientsItem.java while I use the returned ArraysLists.java ?
This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 6 years ago.
I've been trying to store doctor details in SQLite database using signup activity but my app crashes everytime i click on signup button.It shows no error. I've followed many online videos but it just doesn't work for my application
what is the error? Why does the app crash?
dsignup.java
DatabaseHelper1 helper1 = new DatabaseHelper1(this);
public void OnButton_regclick(View v)
{
if(v.getId()== R.id.button_reg)
{
EditText dname = (EditText)findViewById(R.id.dname);
EditText username = (EditText)findViewById(R.id.username);
EditText docemail = (EditText)findViewById(R.id.docemail);
EditText password = (EditText)findViewById(R.id.password);
EditText reg_num = (EditText)findViewById(R.id.reg_num);
EditText dcontact = (EditText)findViewById(R.id.dcontact);
EditText wcontact = (EditText)findViewById(R.id.wcontact);
RadioGroup gender = (RadioGroup) findViewById(R.id.gender);
int selectedid = gender.getCheckedRadioButtonId();
EditText address = (EditText)findViewById(R.id.address);
EditText pincode = (EditText)findViewById(R.id.pincode);
EditText specialization =(EditText)findViewById(R.id.specialization);
EditText experience = (EditText)findViewById(R.id.experience);
EditText category = (EditText)findViewById(R.id.category);
RadioButton rb = (RadioButton)findViewById(selectedid);
String dnamestr = dname.getText().toString();
String docemailstr = docemail.getText().toString();
String usernamestr = username.getText().toString();
String passwordstr = password.getText().toString();
String dcontactstr = dcontact.getText().toString();
String reg_numstr = reg_num.getText().toString();
String specializationstr = specialization.getText().toString();
String experiencestr = experience.getText().toString();
String categorystr = category.getText().toString();
String genderstr = rb.getText().toString();
String pincodestr = pincode.getText().toString();
String addressstr = address.getText().toString();
String wcontactstr = wcontact.getText().toString();
Contact c = new Contact();
c.setDname(dnamestr);
c.setDocemail(docemailstr);
c.setUsername(usernamestr);
c.setPassword(passwordstr);
c.setDcontact(dcontactstr);
c.setReg_num(reg_numstr);
c.setSpecialization(specializationstr);
c.setExperience(experiencestr);
c.setCategory(categorystr);
c.setGender(genderstr);
c.setPincode(pincodestr);
c.setAddress(addressstr);
c.setWcontact(wcontactstr);
helper1.insertContact(c);
}
DatabaseHelper1.java
public class DatabaseHelper1 extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "contacts.db";
private static final String TABLE_NAME1 = "doctors";
private static final String COLUMN_ID1 = "id1";
private static final String COLUMN_DNAME ="dname";
private static final String COLUMN_DCONTACT ="dcontact";
private static final String COLUMN_REG_NUM ="reg_num";
private static final String COLUMN_SPECIALIZATION ="specialization";
private static final String COLUMN_EXPERIENCE ="experience";
private static final String COLUMN_CATEGORY ="category";
private static final String COLUMN_AVAILABLEFROM ="availablefrom";
private static final String COLUMN_PASSWORD ="password";
private static final String COLUMN_USERNAME ="username";
private static final String COLUMN_AVAILABLETO ="availableto";
private static final String COLUMN_GENDER ="gender";
private static final String COLUMN_DOCEMAIL ="docemail";
private static final String COLUMN_PINCODE ="pincode";
private static final String COLUMN_ADDRESS ="address";
private static final String COLUMN_WCONTACT ="wcontact";
private static final String COLUMN_TIMETO ="timeto";
private static final String COLUMN_TIMEFROM ="timefrom";
private static final String COLUMN_LATITUDE ="latitude";
private static final String COLUMN_LONGITUDE ="longitude";
SQLiteDatabase db1;
private static final String TABLE_CREATE1 = "create table doctors (id integer primary key not null, dname text not null,reg_num integer not null , specialization text not null, experience text not null, category text not null," +
"available from text not null, username text not null, availableto text not null, gender text not null, email text not null, pincode integer not null, address text not null " +
" wcontact integer not null, timeto time, timefrom time, latitude float(10,6), longitude float(10,6));";
public DatabaseHelper1(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db1) {
db1.execSQL(TABLE_CREATE1);
this.db1 = db1;
}
public void insertContact(Contact c) {
db1 = this.getWritableDatabase();
ContentValues values = new ContentValues();
String query = "select * from doctors";
Cursor cursor = db1.rawQuery(query , null);
int count = cursor.getCount();
values.put(COLUMN_ID1 , count);
values.put(COLUMN_DNAME, c.getDname());
values.put(COLUMN_DCONTACT, c.getDcontact());
values.put(COLUMN_REG_NUM, c.getReg_num());
values.put(COLUMN_SPECIALIZATION, c.getSpecialization());
values.put(COLUMN_EXPERIENCE, c.getExperience());
values.put(COLUMN_CATEGORY, c.getCategory());
values.put(COLUMN_AVAILABLEFROM, c.getAvailablefrom());
values.put(COLUMN_PASSWORD, c.getPassword());
values.put(COLUMN_USERNAME, c.getUsername());
values.put(COLUMN_AVAILABLETO, c.getAvailableto());
values.put(COLUMN_GENDER, c.getGender());
values.put(COLUMN_DOCEMAIL, c.getDocemail());
values.put(COLUMN_PINCODE, c.getPincode());
values.put(COLUMN_ADDRESS, c.getAddress());
values.put(COLUMN_WCONTACT, c.getWcontact());
//values.put(COLUMN_TIMETO, c.getTimeto());
// values.put(COLUMN_TIMEFROM, c.getTimefrom());
// values.put(COLUMN_LATITUDE, c.getLatitude());
//values.put(COLUMN_LONGITUDE, c.getLongitude());
db1.insert(TABLE_NAME1, null, values);
db1.close();
}
public String searchPass(String username)
{
db1 = this.getReadableDatabase();
String query = "select uname, pass from "+TABLE_NAME1;
Cursor cursor = db1.rawQuery(query , null);
String a, b;
b = "not found";
if(cursor.moveToFirst())
{
do{
a = cursor.getString(0);
if(a.equals(username))
{
b = cursor.getString(1);
break;
}
}
while(cursor.moveToNext());
}
return b;
}
#Override
public void onUpgrade(SQLiteDatabase db1, int oldVersion, int newVersion) {
String query = "DROP TABLE IF EXISTS "+TABLE_NAME1;
db1.execSQL(query);
this.onCreate(db1);
}
}
Contact.java
public class Contact {
String name ,email,uname,pass,gender1,dname,dcontact,reg_num,specialization, experience, category, availablefrom, password, username, availableto,gender,docemail,pincode,address,wcontact;
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return this.name;
}
public void setEmail(String email)
{
this.email = email;
}
public String getEmail()
{
return this.email;
}
public void setUname(String uname)
{
this.uname = uname;
}
public String getUname()
{
return this.uname;
}
public void setPass(String pass)
{
this.pass = pass;
}
public String getPass()
{
return this.pass;
}
public void setGender1(String gender)
{
this.gender1 = gender;
}
public String getGender1()
{
return this.gender1;
}
public void setDname(String dname)
{
this.dname = dname;
}
public String getDname()
{
return this.dname;
}
public void setReg_num(String reg_num)
{
this.reg_num = reg_num;
}
public String getReg_num()
{
return this.reg_num;
}
public void setDcontact(String dcontact)
{
this.name = dcontact;
}
public String getDcontact()
{
return this.dcontact;
}
public void setSpecialization(String specialization)
{
this.specialization = specialization;
}
public String getSpecialization()
{
return this.specialization;
}
public void setExperience(String experience)
{
this.experience = experience;
}
public String getExperience()
{
return this.experience;
}
public void setCategory(String category)
{
this.category = category;
}
public String getCategory()
{
return this.category;
}
public void setAvailablefrom(String availablefrom)
{
this.availablefrom = availablefrom;
}
public String getAvailablefrom()
{
return this.availablefrom;
}
public void setPassword(String password)
{
this.password = password;
}
public String getPassword()
{
return this.password;
}
public void setUsername(String username)
{
this.username = username;
}
public String getUsername()
{
return this.username;
}
public void setAvailableto(String availableto)
{
this.availableto = availableto;
}
public String getAvailableto()
{
return this.availableto;
}
public void setGender(String gender)
{
this.gender = gender;
}
public String getGender()
{
return this.gender;
}
public void setDocemail(String docemail)
{
this.docemail = docemail;
}
public String getDocemail()
{
return this.docemail;
}
public void setPincode(String pincode) {this.pincode = pincode;}
public String getPincode()
{
return this.pincode;
}
public void setAddress(String address)
{
this.address = address;
}
public String getAddress()
{
return this.address;
}
public void setWcontact(String wcontact)
{
this.wcontact = wcontact;
}
public String getWcontact()
{
return this.wcontact;
}
public void setTimeto(String timeto)
{
this.timeto = timeto;
}
public String getTimeto() {return this.timeto;}
public void setTimefrom(String timefrom)
{
this.timefrom = timefrom;
}
public String getTimefrom()
{
return this.timefrom;
}
}
Try to put some order on your code because is not easy read it. Also, create a method where you can inicialite your widgets, something like this:
public static void startCom(){
text1 = (textView) findById....
.
.
.
}
Only on the method onCreate you invoke startComp, just to save the order of the code.