SQLite database columns stay Null on update method in different activities - android

I use SQLite database to save data from different activities in my app. in the first activity I use the add method to create a row in the table and the next activities use update method to update the created columns. my previous question which is somehow similar can be found here :
Previous Question
Previously my problem was with not using setId. Now my problem is with the third activity. after calling the update method, the columns stay Null. I tried passing the id from NewProjectActivity to the MainActivity and then to the IntensityActivity but I don't know why the columns don't get updated. Here are the codes :
SQLite Helper:
public class SQLiteHelper extends SQLiteOpenHelper implements ProjectDAO {
public SQLiteHelper(Context context) {
super(context, "my_db", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL("CREATE TABLE tbl_project_info (id INTEGER PRIMARY KEY," +
"name TEXT," +
"company_name TEXT," +
"address TEXT," +
"length1 TEXT," +
"length2 TEXT," +
"length3 TEXT," +
"length4 TEXT," +
"length5 TEXT," +
"diameter1 Text," +
"diameter2 Text," +
"diameter3 Text," +
"diameter4 Text," +
"diameter5 Text," +
"surface Text," +
"soilResistance Text," +
"intensity Text," +
"allowedIntensity Text," +
"intensityResult Text)");
} catch (SQLiteException e) {
Log.e("SQLITE", "onCreate: " + e.toString());
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
#Override
public long addProject(Project project) {
SQLiteDatabase db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", project.getName());
contentValues.put("company_name", project.getCompany_name());
contentValues.put("address", project.getAddress());
contentValues.put("length1", project.getLength1());
contentValues.put("length2", project.getLength2());
contentValues.put("length3", project.getLength3());
contentValues.put("length4", project.getLength4());
contentValues.put("length5", project.getLength5());
contentValues.put("diameter1", project.getDiameter1());
contentValues.put("diameter2", project.getDiameter2());
contentValues.put("diameter3", project.getDiameter3());
contentValues.put("diameter4", project.getDiameter4());
contentValues.put("diameter5", project.getDiameter5());
contentValues.put("surface", project.getSurface());
contentValues.put("soilResistance", project.getSoilResistance());
contentValues.put("intensity", project.getIntensity());
contentValues.put("allowedIntensity", project.getAllowedIntensity());
contentValues.put("intensityResult", project.getIonS());
long result = db.insert("tbl_project_info", null, contentValues);
db.close();
return result;
}
#Override
public int getProjectsCount() {
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM tbl_project_info", null);
int count = cursor.getCount();
cursor.close();
db.close();
return count;
}
#Override
public boolean updateProject(Project project) {
SQLiteDatabase db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("length1", project.getLength1());
contentValues.put("length2", project.getLength2());
contentValues.put("length3", project.getLength3());
contentValues.put("length4", project.getLength4());
contentValues.put("length5", project.getLength5());
contentValues.put("diameter1", project.getDiameter1());
contentValues.put("diameter2", project.getDiameter2());
contentValues.put("diameter3", project.getDiameter3());
contentValues.put("diameter4", project.getDiameter4());
contentValues.put("diameter5", project.getDiameter5());
contentValues.put("surface", project.getSurface());
contentValues.put("soilResistance", project.getSoilResistance());
contentValues.put("intensity", project.getIntensity());
contentValues.put("allowedIntensity", project.getAllowedIntensity());
contentValues.put("intensityResult", project.getIonS());
db.update("tbl_project_info", contentValues, "id = ?", new String[]{String.valueOf(project.getId())});
db.close();
return true;
}
#Override
public List<Project> getAllProjects() {
List<Project> projects = new ArrayList<>();
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM tbl_project_info", null);
if (cursor.moveToFirst()) {
do {
Project project = new Project();
project.setName(cursor.getString(0));
project.setCompany_name(cursor.getString(1));
project.setAddress(cursor.getString(2));
projects.add(project);
} while (cursor.moveToNext());
}
return projects;
}
}
NewProjectActivity :
public class NewProjectActivity extends AppCompatActivity {
private ProjectDAO projectDAO;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_project);
projectDAO = DBInjector.provideProjectDao(this);
setupViews();
}
private void setupViews() {
final EditText projectNameET = findViewById(R.id.et_newProject_projectName);
final EditText companyNameET = findViewById(R.id.et_newProject_companyName);
final EditText addressET = findViewById(R.id.et_newProject_address);
Button saveInfoBTN = findViewById(R.id.btn_newProject_saveInfo);
saveInfoBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
long projectID = -1;
if (projectNameET.length() > 0) {
if (companyNameET.length() > 0) {
if (addressET.length() > 0) {
Project project = new Project();
project.setName(projectNameET.getText().toString());
project.setCompany_name(companyNameET.getText().toString());
project.setAddress(addressET.getText().toString());
projectID = projectDAO.addProject(project);
if (projectID > 0){
Toast.makeText(NewProjectActivity.this, "Success", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(NewProjectActivity.this, "Failed", Toast.LENGTH_SHORT).show();
}
}
}else {
companyNameET.setError("company name not entered");
}
}else{
projectNameET.setError("project name not entered");
}
PersonalInfoSharedPrefManager manager = new PersonalInfoSharedPrefManager(NewProjectActivity.this);
manager.setID(projectID);
Intent intent = new Intent(NewProjectActivity.this,MainActivity.class);
intent.putExtra("IE_PROJECTID",projectID);
startActivity(intent);
}
});
}
}
MainActivity :
public class MainActivity extends AppCompatActivity {
private ProjectDAO projectDAO;
private long mProjectID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
projectDAO = DBInjector.provideProjectDao(this);
mProjectID = getIntent().getLongExtra("IE_PROJECTID",0);
final EditText lengthET1 = findViewById(R.id.et_main_length1);
final EditText lengthET2 = findViewById(R.id.et_main_length2);
final EditText lengthET3 = findViewById(R.id.et_main_length3);
final EditText lengthET4 = findViewById(R.id.et_main_length4);
final EditText lengthET5 = findViewById(R.id.et_main_length5);
final EditText diameterET1 = findViewById(R.id.et_main_diameter1);
final EditText diameterET2 = findViewById(R.id.et_main_diameter2);
final EditText diameterET3 = findViewById(R.id.et_main_diameter3);
final EditText diameterET4 = findViewById(R.id.et_main_diameter4);
final EditText diameterET5 = findViewById(R.id.et_main_diameter5);
Button calculateButton = findViewById(R.id.btn_main_calculate);
calculateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
float Le1 = 0;
if (lengthET1.length() > 0) {
String L1 = lengthET1.getText().toString();
Le1 = Float.parseFloat(L1);
}
float Di1 = 0;
if (diameterET1.length() > 0) {
String D1 = diameterET1.getText().toString();
Di1 = Float.parseFloat(D1);
}
float Le2 = 0;
if (lengthET2.length() > 0) {
String L2 = lengthET2.getText().toString();
Le2 = Float.parseFloat(L2);
}
float Di2 = 0;
if (diameterET2.length() > 0) {
String D2 = diameterET2.getText().toString();
Di2 = Float.parseFloat(D2);
}
float Le3 = 0;
if (lengthET3.length() > 0) {
String L3 = lengthET3.getText().toString();
Le3 = Float.parseFloat(L3);
}
float Di3 = 0;
if (diameterET3.length() > 0) {
String D3 = diameterET3.getText().toString();
Di3 = Float.parseFloat(D3);
}
float Le4 = 0;
if (lengthET4.length() > 0) {
String L4 = lengthET4.getText().toString();
Le4 = Float.parseFloat(L4);
}
float Di4 = 0;
if (diameterET4.length() > 0) {
String D4 = diameterET4.getText().toString();
Di4 = Float.parseFloat(D4);
}
float Le5 = 0;
if (lengthET5.length() > 0) {
String L5 = lengthET5.getText().toString();
Le5 = Float.parseFloat(L5);
}
float Di5 = 0;
if (diameterET5.length() > 0) {
String D5 = diameterET5.getText().toString();
Di5 = Float.parseFloat(D5);
}
final float Surface1 = (float) (Le1 * Di1 * Math.PI);
final float Surface2 = (float) (Le2 * Di2 * Math.PI);
final float Surface3 = (float) (Le3 * Di3 * Math.PI);
final float Surface4 = (float) (Le4 * Di4 * Math.PI);
final float Surface5 = (float) (Le5 * Di5 * Math.PI);
final float Surface = Surface1 + Surface2 + Surface3 + Surface4 + Surface5;
long projectID = -1;
Intent intent = new Intent(MainActivity.this, IntensityActivity.class);
if (Surface == 0) {
Toast.makeText(MainActivity.this, "No numbers are entered", Toast.LENGTH_SHORT).show();
} else {
intent.putExtra("Result", Surface);
intent.putExtra("IE_PROJECTID",projectID);
startActivity(intent);
}
PersonalInfoSharedPrefManager manager = new PersonalInfoSharedPrefManager(MainActivity.this);
manager.setSuface(Surface);
Project project = new Project();
project.setId(mProjectID);
project.setLength1(lengthET1.getText().toString());
project.setDiameter1(diameterET1.getText().toString());
project.setLength2(lengthET2.getText().toString());
project.setDiameter2(diameterET2.getText().toString());
project.setLength3(lengthET3.getText().toString());
project.setDiameter3(diameterET3.getText().toString());
project.setLength4(lengthET4.getText().toString());
project.setDiameter4(diameterET4.getText().toString());
project.setLength5(lengthET5.getText().toString());
project.setDiameter5(diameterET5.getText().toString());
project.setSurface(String.valueOf(Surface));
projectDAO.updateProject(project);
}
});
}
}
IntensityActivity :
public class IntensityActivity extends AppCompatActivity {
private ProjectDAO projectDAO;
private long mProjectID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intensity);
projectDAO = DBInjector.provideProjectDao(this);
mProjectID = getIntent().getLongExtra("IE_PROJECTID",0);
final float Result = getIntent().getFloatExtra("Result",0);
final Button resistanceBTN1 = findViewById(R.id.btn_intensity_R1);
final Button resistanceBTN2 = findViewById(R.id.btn_intensity_R2);
final Button resistanceBTN3 = findViewById(R.id.btn_intensity_R3);
final Button resistanceBTN4 = findViewById(R.id.btn_intensity_R4);
final Button resistanceBTN5 = findViewById(R.id.btn_intensity_R5);
final View RL = findViewById(R.id.rl_intensity_allowedIntensity);
final TextView allowedResistance = findViewById(R.id.tv_intensity_allowedIntensityNumber);
final TextView surfaceNumber = findViewById(R.id.tv_intensity_surfaceNumber);
final EditText intensityNumber = findViewById(R.id.et_intensity_intensityNumber);
Button calculateButton = findViewById(R.id.btn_intensity_calculate);
final Button goToVoltageButton = findViewById(R.id.btn_intensity_goToVoltage);
final TextView formulaResultNumber = findViewById(R.id.tv_intensity_resultNumber);
String Sur = Float.toString(Result);
surfaceNumber.setText(Sur);
final double R1 = Result*0.250;
final double R2 = Result*0.125;
final double R3 = Result*0.050;
final double R4 = Result*0.025;
final double R5 = Result*0.010;
final String Re1 = Double.toString(R1);
final String Re2 = Double.toString(R2);
final String Re3 = Double.toString(R3);
final String Re4 = Double.toString(R4);
final String Re5 = Double.toString(R5);
resistanceBTN1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RL.setVisibility(View.VISIBLE);
allowedResistance.setText(Re1);
}
});
resistanceBTN2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RL.setVisibility(View.VISIBLE);
allowedResistance.setText(Re2);
}
});
resistanceBTN3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RL.setVisibility(View.VISIBLE);
allowedResistance.setText(Re3);
}
});
resistanceBTN4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RL.setVisibility(View.VISIBLE);
allowedResistance.setText(Re4);
}
});
resistanceBTN5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RL.setVisibility(View.VISIBLE);
allowedResistance.setText(Re5);
}
});
calculateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String I = intensityNumber.getText().toString();
float In = Float.parseFloat(I);
float R = In/Result;
String Res = String.valueOf(R);
formulaResultNumber.setText(Res);
goToVoltageButton.setVisibility(View.VISIBLE);
PersonalInfoSharedPrefManager manager = new PersonalInfoSharedPrefManager(IntensityActivity.this);
manager.setIntensity(In);
}
});
goToVoltageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(IntensityActivity.this,SimpleVoltage.class);
startActivity(intent);
Project project = new Project();
project.setId(mProjectID);
project.setAllowedIntensity(String.valueOf(allowedResistance));
project.setIntensity(intensityNumber.getText().toString());
projectDAO.updateProject(project);
}
});
}
}

From MainActivity to IntensityActivity, What I found is that you are always passing -1 in Project ID
final float Surface = Surface1 + Surface2 + Surface3 + Surface4 + Surface5;
long projectID = -1;
Intent intent = new Intent(MainActivity.this, IntensityActivity.class);
if (Surface == 0) {
Toast.makeText(MainActivity.this, "No numbers are entered", Toast.LENGTH_SHORT).show();
} else {
intent.putExtra("Result", Surface);
intent.putExtra("IE_PROJECTID",projectID);
startActivity(intent);
}
Instead you can pass the same ID you have got on this activity from Intent
Just update your code in MainActivity as below and pass mProjectID.
final float Surface = Surface1 + Surface2 + Surface3 + Surface4 + Surface5;
long projectID = -1;
Intent intent = new Intent(MainActivity.this, IntensityActivity.class);
if (Surface == 0) {
Toast.makeText(MainActivity.this, "No numbers are entered", Toast.LENGTH_SHORT).show();
} else {
intent.putExtra("Result", Surface);
intent.putExtra("IE_PROJECTID",mProjectID);
startActivity(intent);
}
Hope this will help.

try this way in your update method,
db.update("tbl_project_info", contentValues, "id="+String.valueOf(project.getId()), null);
Also you need to change following line into MainActivity.java
long projectID = -1;
to
long projectID = mProjectID;

Related

Transaction not updating property in android firestore

I am trying to add a feature like or dislike to my post(Question). But it is not updating the like button image.
public class QuestionDetailActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "QuestionDetailActivity";
private Context mContext;
private TextView questionTitleTv;
private RadioGroup radioLL;
private EditText answerEt;
private LinearLayout checkboxLL;
private LinearLayout commentLL;
private FirebaseFirestore db = null;
private String questionID;
private String userID;
private TextView likeCountTv,favouriteCountTv;
private boolean isLikedByUser = false,isFavouriteByUser = false;
private DocumentReference questionRef;
private QuestionBO questionBO;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question_detail);
mContext = QuestionDetailActivity.this;
db = FirebaseFirestore.getInstance();
userID = "V5BUeBFYR8WKOQUiBFxKrfMHK8Y2";
questionTitleTv = findViewById(R.id.tv_question_title);
radioLL = findViewById(R.id.ll_radio);
answerEt = findViewById(R.id.et_answer);
checkboxLL = findViewById(R.id.ll_checkbox);
commentLL = findViewById(R.id.ll_comments);
likeCountTv = findViewById(R.id.tv_like_count);
favouriteCountTv = findViewById(R.id.tv_favourite_count);
likeCountTv.setOnClickListener(this);
favouriteCountTv.setOnClickListener(this);
if (getIntent() != null) {
questionID = getIntent().getExtras().getString("keyQuestionID", "");
}
questionRef = db.collection("questionCollection").document(questionID);
if (!questionID.isEmpty()) {
getQuestionDetail();
///showComments();
updateFavouriteAndLikeIcons();
}
}
private void updateFavouriteAndLikeIcons() {
questionRef.collection("favouriteCollection").document(userID).get()
.addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
if(documentSnapshot.exists()){
isFavouriteByUser = true;
// and make it blue
Drawable image = getResources().getDrawable( R.drawable.icn_fav_yes );
int h = image.getIntrinsicHeight();
int w = image.getIntrinsicWidth();
image.setBounds( 0, 0, w, h );
favouriteCountTv.setCompoundDrawables( image, null, null, null );
}
}
});
questionRef.collection("likeCollection").document(userID).get()
.addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
if(documentSnapshot.exists()){
boolean isLiked = documentSnapshot.getBoolean(userID);
if(isLiked){
isLikedByUser = true;
// and make it blue
Drawable image = getResources().getDrawable( R.drawable.icn_like_yes );
int h = image.getIntrinsicHeight();
int w = image.getIntrinsicWidth();
image.setBounds( 0, 0, w, h );
likeCountTv.setCompoundDrawables( image, null, null, null );
}
else{//dislike
}
}
}
});
}
private void showComments() {
db.collection("commentCollection").whereEqualTo("questionID", questionID)
.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
if (queryDocumentSnapshots.isEmpty()) {
Log.d(TAG, "onSuccess: LIST EMPTY");
return;
} else {
// Convert the whole Query Snapshot to a list
// of objects directly! No need to fetch each
// document.
List<CommentBO> commentList = queryDocumentSnapshots.toObjects(CommentBO.class);
if (commentList != null && commentList.size() > 0) {
for (int x = 0; x < commentList.size(); x++) {
try {
LinearLayout.LayoutParams childParam = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
childParam.setMargins(20, 10, 0, 0);
View commentByView = LayoutInflater.from(mContext).inflate(R.layout.item_comment, null);
TextView tvCommenter = (TextView) commentByView.findViewById(R.id.item_tv_commenter_name);
TextView tvCommenterComment = (TextView) commentByView.findViewById(R.id.item_tv_commenter_comment);
TextView tvCommentDate = (TextView) commentByView.findViewById(R.id.item_tv_comment_date);
tvCommenter.setText(commentList.get(x).getCommentedBy());
tvCommenterComment.setText(commentList.get(x).getComment());
///tvCommentDate.setText();
commentLL.addView(commentByView, childParam);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
});
}
private void getQuestionDetail() {
questionRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
Log.d(TAG, "DocumentSnapshot data: " + document.getData());
questionBO = document.toObject(QuestionBO.class);
updateView(questionBO);
} else {
Log.d(TAG, "No such document");
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});
}
private void updateView(QuestionBO mQuestionBO) {
if (mQuestionBO != null) {
questionTitleTv.setText(mQuestionBO.getTitle());
likeCountTv.setText(mQuestionBO.getTotalLikes() + "");
favouriteCountTv.setText(mQuestionBO.getTotalFavourites() + "");
switch (mQuestionBO.getQuestionType()) {
case CHECKBOX:
checkboxLL.setVisibility(View.VISIBLE);
if (mQuestionBO.getOptions() != null && mQuestionBO.getOptions().size() > 0) {
checkboxLL.removeAllViews();
for (int x = 0; x < mQuestionBO.getOptions().size(); x++) {
final CheckBox subCheckbox = new CheckBox(mContext);
subCheckbox.setText(mQuestionBO.getOptions().get(x));
subCheckbox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
checkboxLL.addView(subCheckbox, new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
}
}
break;
case RADIO:
radioLL.setVisibility(View.VISIBLE);
if (mQuestionBO.getOptions() != null && mQuestionBO.getOptions().size() > 0) {
radioLL.removeAllViews();
for (int x = 0; x < mQuestionBO.getOptions().size(); x++) {
final RadioButton subRadio = new RadioButton(mContext);
subRadio.setText(mQuestionBO.getOptions().get(x));
radioLL.addView(subRadio, new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
}
}
break;
case DESCRIPTIVE:
answerEt.setVisibility(View.VISIBLE);
break;
}
}
}
private void likeOrDislikeThisQuestion(){
final Task<Boolean> booleanTask = db.runTransaction(new Transaction.Function<Boolean>() {
#Nullable
#Override
public Boolean apply(#NonNull Transaction transaction) throws FirebaseFirestoreException {
DocumentReference likeRef = questionRef.collection("likeCollection")
.document(userID);
Map<String,Object> map = new HashMap<>();
DocumentSnapshot snapshot = transaction.get(likeRef);
if(snapshot.exists()){ // it means this is a favourite question of this user.
if(snapshot.getBoolean(questionID) && isLikedByUser){
isLikedByUser = false;
map.put(questionID,isLikedByUser);
transaction.update(likeRef,map);
int numberOfLikes = questionBO.getTotalLikes();
transaction.update(questionRef,"totalLikes",--numberOfLikes);
likeCountTv.setText(numberOfLikes + "");
return isLikedByUser;
}
else if(!snapshot.getBoolean(questionID) && !isLikedByUser){
isLikedByUser = true;
map.put(questionID,isLikedByUser);
transaction.update(likeRef,map);
int numberOfLikes = questionBO.getTotalLikes();
transaction.update(questionRef,"totalLikes",-++numberOfLikes);
likeCountTv.setText(numberOfLikes + "");
return isLikedByUser;
}
}
else {
isLikedByUser = !isLikedByUser;
map.put(questionID,isLikedByUser);// pass oposite of it..
transaction.set(likeRef,map);
int numberOfLikes = questionBO.getTotalLikes();
if(isLikedByUser)
++numberOfLikes;
else
--numberOfLikes;
transaction.update(questionRef,"totalLikes",numberOfLikes);
likeCountTv.setText(numberOfLikes + "");
return isLikedByUser;
}
return null;
}
});
booleanTask.addOnSuccessListener(new OnSuccessListener<Boolean>() {
#Override
public void onSuccess(Boolean isLiked) {
if(isLiked == null){
}
else if(isLiked){
Drawable image = getResources().getDrawable( R.drawable.icn_like_yes );
int h = image.getIntrinsicHeight();
int w = image.getIntrinsicWidth();
image.setBounds( 0, 0, w, h );
likeCountTv.setCompoundDrawables( image, null, null, null );
}
else{
Drawable image = getResources().getDrawable( R.drawable.icn_like_no );
int h = image.getIntrinsicHeight();
int w = image.getIntrinsicWidth();
image.setBounds( 0, 0, w, h );
likeCountTv.setCompoundDrawables( image, null, null, null );
}
}
});
}
private void favouriteOrDisFavouriteQuestion(){
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.tv_like_count:
likeOrDislikeThisQuestion();
break;
case R.id.tv_favourite_count:
break;
}
}
}
I updated icon using updateFavouriteAndLikeIcons() for the first time. then when user clicks on like button I called likeOrDislikeThisQuestion() . Counter updating but left drawable not updating. and sometimes variable isLikedByUser become false .
If the question is already liked then likeCollection must have that Document. if that document don't exist it means User didn't like or dislike it.
My architecture of db is like
- likeCollection
userID (Document ID)
questionID = true // true for like and false for dislike..
From Firebase docs :
Do not modify application state inside of your transaction functions. Doing so will introduce concurrency issues, because transaction functions can run multiple times and are not guaranteed to run on the UI thread. Instead, pass information you need out of your transaction functions.
This is what happens here, you have to run every application modifications inside a listener on your variable booleanTask. Do not change class variable in the transaction's apply method.

uses unchecked or unsafe operations. Recompile with -Xlint:unchecked for details in compaling the code

Hello while compiling my app am getting an error like this.what is this warning am unable to finding an issue.
uses unchecked or unsafe operations.
Recompile with -Xlint:unchecked for details.
can any one please resolve the issues.In the below code have class named as selecttimeractivity simple it's showing unsafe operations and re-compile.
public class SelectTimerActivity extends AppCompatActivity {
private static final String TAG = SelectTimerActivity.class.getSimpleName();
#BindView(R.id.back)
TextView mBack;
#BindView(R.id.setTimer)
TextView mSetTimer;
#BindView(R.id.toolBar)
Toolbar mToolBar;
#BindView(R.id.customeSeekBar)
RangeSeekBar mCustomeSeekBar;
#BindView(R.id.dimming_picker)
NumberPicker mDimmingPicker;
private SharedPreferences mPref;
private SolarBLEPacket mSolarBlePacket = new SolarBLEPacket();
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_timer);
ButterKnife.bind(this);
mPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
final String[] dimmingValues = new String[]{"0%", "10%", "20%", "30%", "40%", "50%", "60%", "70%", "80%", "90%", "100%"};
initDimmingPicker(dimmingValues);
Long currentMin = 1L, currentMax = 66000L;
mCustomeSeekBar.setRangeValues(currentMin, currentMax);
attachColorToNumberPicker();
}
private void attachColorToNumberPicker() {
int count = mDimmingPicker.getChildCount();
for (int i = 0; i < count; i++) {
View child = mDimmingPicker.getChildAt(i);
if (child instanceof EditText) {
try {
Field selectorWheelPaintField = mDimmingPicker.getClass()
.getDeclaredField("mSelectorWheelPaint");
selectorWheelPaintField.setAccessible(true);
((Paint) selectorWheelPaintField.get(mDimmingPicker)).setColor(Color.WHITE);
((EditText) child).setTextColor(Color.WHITE);
mDimmingPicker.invalidate();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
private void initDimmingPicker(String[] dimmingValues) {
mDimmingPicker.setEnabled(true);
mDimmingPicker.setMinValue(0);
mDimmingPicker.setMaxValue(dimmingValues.length - 1);
mDimmingPicker.setDisplayedValues(dimmingValues);
mDimmingPicker.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
mDimmingPicker.setWrapSelectorWheel(false);
}
#OnClick({R.id.back, R.id.setTimer})
public void onClick(View view) {
switch (view.getId()) {
case R.id.back:
setResult(RESULT_OK, new Intent());
finish();
break;
case R.id.setTimer:
Number selectedMinValue = mCustomeSeekBar.getSelectedMinValue();
Number selectedMaxValue = mCustomeSeekBar.getSelectedMaxValue();
String timer1 = mCustomeSeekBar.convertSecondsToHMmSs(selectedMinValue.longValue());
String timer2 = mCustomeSeekBar.getDiffTime(selectedMinValue.longValue(), selectedMaxValue.longValue());
String timer1Command = buildDimDurnCmd(timer1);
String timer2Command = builtDimmOffCommand(timer2);
String brighnessCommand = builtBrightnessCommand();
mPref.edit().putString(Constants.TIMER_ONE_CMD, timer1Command).commit();
mPref.edit().putString(Constants.TIMER_TWO_CMD, timer2Command).commit();
mPref.edit().putString(Constants.BRIGHTNESS_CMD, brighnessCommand).commit();
Intent intent = new Intent();
setResult(RESULT_OK, intent);
finish();
break;
}
}
private String builtBrightnessCommand() {
final String[] dimmingValues = new String[]{"0%", "10%", "20%", "30%", "40%", "50%", "60%", "70%", "80%", "90%", "100%"};
String dimmingValue = dimmingValues[mDimmingPicker.getValue()];
String replacedString = dimmingValue.replace("%", "");
String command = "";
if (!TextUtils.isEmpty(replacedString)) {
if (replacedString.length() == 1) {
command = "bright 00" + replacedString;
} else if (replacedString.length() == 2) {
command = "bright 0" + replacedString;
} else {
command = "bright " + replacedString;
}
}
Log.d(TAG, "!! Built with Brightness Command...." + command);
return mSolarBlePacket.generatePacket(command, "00");
}
private String buildDimDurnCmd(String command) {
String[] commandArray = command.split(":");
String hour = commandArray[0];
String min = commandArray[1];
String timerCommand = "dimdurn " + hour + "h" + min;
Log.d(TAG, "!! Final Timer Command is " + timerCommand);
return mSolarBlePacket.generatePacket(timerCommand, "00");
}
private String builtDimmOffCommand(String command) {
String[] commandArray = command.split(":");
String hour = commandArray[0];
String min = commandArray[1];
String timerCommand = "dimmoff " + hour + "h" + min;
Log.d(TAG, "!! Final Timer Command is " + timerCommand);
return mSolarBlePacket.generatePacket(timerCommand, "00");
}

Saving/Storeing an external image into SQLite Database

I have a book-App, where I scan a book with barcodescanner and retrieving the information from googlebooksapi.
At the moment I can save the general bookinfos, title, author, date, rating and shelf (where i want to display the book) in my SQLite database
Now I want to save the bookcover, which comes with the googleapi, too.
Can you tell me how I can save the image in my SQlite Database. By looking for solution I realized that I have to blob the image. but I dont know how.
Following my activties.
ScanActivity.java -> at the end of the code, I save the book data into sql db
public class ScanActivity extends AppCompatActivity implements OnClickListener {
private Button scanBtn, previewBtn, linkBtn, addBookBtn, librarybtn;
public TextView authorText, titleText, descriptionText, dateText, ratingCountText;
public EditText shelfText;
private LinearLayout starLayout;
private ImageView thumbView;
private ImageView[] starViews;
private Bitmap thumbImg;
public BookDBHelper bookDBHelper;
public SQLiteDatabase sqLiteDatabase1;
public Context context1 = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan);
//Fonts
Typeface myTypeface = Typeface.createFromAsset(getAssets(), "Lobster.ttf");
Button myButtonViewScan = (Button) findViewById(R.id.scan_button);
myButtonViewScan.setTypeface(myTypeface);
TextView myWheretoSaveTextView = (TextView) findViewById(R.id.textView_wheretosave);
myWheretoSaveTextView.setTypeface(myTypeface);
//Scanbutton
scanBtn = (Button) findViewById(R.id.scan_button);
scanBtn.setOnClickListener(this);
//Preview Button
previewBtn = (Button) findViewById(R.id.preview_btn);
previewBtn.setVisibility(View.GONE);
previewBtn.setOnClickListener(this);
//Weblink Button
linkBtn = (Button) findViewById(R.id.link_btn);
linkBtn.setVisibility(View.GONE);
linkBtn.setOnClickListener(this);
/* //AddBookBtn
addBookBtn= (Button)findViewById(R.id.btn_savebook);
addBookBtn.setVisibility(View.GONE);
addBookBtn.setOnClickListener(this);
//LibraryButton
librarybtn = (Button) findViewById(R.id.btn_maps);
librarybtn.setVisibility(View.GONE);
librarybtn.setOnClickListener(this);
*/
authorText = (TextView) findViewById(R.id.book_author);
titleText = (TextView) findViewById(R.id.book_title);
descriptionText = (TextView) findViewById(R.id.book_description);
dateText = (TextView) findViewById(R.id.book_date);
starLayout = (LinearLayout) findViewById(R.id.star_layout);
ratingCountText = (TextView) findViewById(R.id.book_rating_count);
thumbView = (ImageView) findViewById(R.id.thumb);
shelfText = (EditText) findViewById(R.id.editText_wheretosave);
starViews = new ImageView[5];
for (int s = 0; s < starViews.length; s++) {
starViews[s] = new ImageView(this);
}
starViews = new ImageView[5];
for (int s = 0; s < starViews.length; s++) {
starViews[s] = new ImageView(this);
}
}
public void onClick(View v) {
if (v.getId() == R.id.scan_button) {
IntentIntegrator scanIntegrator = new IntentIntegrator(this);
scanIntegrator.initiateScan();
} else if (v.getId() == R.id.link_btn) {
//get the url tag
String tag = (String) v.getTag();
//launch the url
Intent webIntent = new Intent(Intent.ACTION_VIEW);
webIntent.setData(Uri.parse(tag));
startActivity(webIntent);
} else if (v.getId() == R.id.preview_btn) {
String tag = (String) v.getTag();
Intent intent = new Intent(this, EmbeddedBook.class);
intent.putExtra("isbn", tag);
startActivity(intent);
//launch preview
}
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
//retrieve result of scanning - instantiate ZXing object
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
//check we have a valid result
if (scanningResult != null) {
String scanContent = scanningResult.getContents();
//get format name of data scanned
String scanFormat = scanningResult.getFormatName();
previewBtn.setTag(scanContent);
if (scanContent != null && scanFormat != null && scanFormat.equalsIgnoreCase("EAN_13")) {
String bookSearchString = "https://www.googleapis.com/books/v1/volumes?" +
"q=isbn:" + scanContent + "&key=AIzaSyDminlOe8YitHijWd51n7-w2h8W1qb5PP0";
new GetBookInfo().execute(bookSearchString);
} else {
Toast toast = Toast.makeText(getApplicationContext(),
"Not a valid scan!", Toast.LENGTH_SHORT);
toast.show();
}
Log.v("SCAN", "content: " + scanContent + " - format: " + scanFormat);
} else {
//invalid scan data or scan canceled
Toast toast = Toast.makeText(getApplicationContext(),
"No book scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
}
private class GetBookInfo extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... bookURLs) {
StringBuilder bookBuilder = new StringBuilder();
for (String bookSearchURL : bookURLs) {
HttpClient bookClient = new DefaultHttpClient();
try {
HttpGet bookGet = new HttpGet(bookSearchURL);
HttpResponse bookResponse = bookClient.execute(bookGet);
StatusLine bookSearchStatus = bookResponse.getStatusLine();
if (bookSearchStatus.getStatusCode() == 200) {
HttpEntity bookEntity = bookResponse.getEntity();
InputStream bookContent = bookEntity.getContent();
InputStreamReader bookInput = new InputStreamReader(bookContent);
BufferedReader bookReader = new BufferedReader(bookInput);
String lineIn;
while ((lineIn = bookReader.readLine()) != null) {
bookBuilder.append(lineIn);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
return bookBuilder.toString();
}
protected void onPostExecute(String result) {
try {
previewBtn.setVisibility(View.VISIBLE);
JSONObject resultObject = new JSONObject(result);
JSONArray bookArray = resultObject.getJSONArray("items");
JSONObject bookObject = bookArray.getJSONObject(0);
JSONObject volumeObject = bookObject.getJSONObject("volumeInfo");
try {
titleText.setText(volumeObject.getString("title"));
} catch (JSONException jse) {
titleText.setText("");
jse.printStackTrace();
}
StringBuilder authorBuild = new StringBuilder("");
try {
JSONArray authorArray = volumeObject.getJSONArray("authors");
for (int a = 0; a < authorArray.length(); a++) {
if (a > 0) authorBuild.append(", ");
authorBuild.append(authorArray.getString(a));
}
authorText.setText(authorBuild.toString());
} catch (JSONException jse) {
authorText.setText("");
jse.printStackTrace();
}
try {
dateText.setText(volumeObject.getString("publishedDate"));
} catch (JSONException jse) {
dateText.setText("");
jse.printStackTrace();
}
try {
descriptionText.setText("DESCRIPTION: " + volumeObject.getString("description"));
} catch (JSONException jse) {
descriptionText.setText("");
jse.printStackTrace();
}
try {
double decNumStars = Double.parseDouble(volumeObject.getString("averageRating"));
int numStars = (int) decNumStars;
starLayout.setTag(numStars);
starLayout.removeAllViews();
for (int s = 0; s < numStars; s++) {
starViews[s].setImageResource(R.drawable.star);
starLayout.addView(starViews[s]);
}
} catch (JSONException jse) {
starLayout.removeAllViews();
jse.printStackTrace();
}
try {
ratingCountText.setText(volumeObject.getString("ratingsCount") + " ratings");
} catch (JSONException jse) {
ratingCountText.setText("");
jse.printStackTrace();
}
try {
boolean isEmbeddable = Boolean.parseBoolean
(bookObject.getJSONObject("accessInfo").getString("embeddable"));
if (isEmbeddable) previewBtn.setEnabled(true);
else previewBtn.setEnabled(false);
} catch (JSONException jse) {
previewBtn.setEnabled(false);
jse.printStackTrace();
}
try {
linkBtn.setTag(volumeObject.getString("infoLink"));
linkBtn.setVisibility(View.VISIBLE);
} catch (JSONException jse) {
linkBtn.setVisibility(View.GONE);
jse.printStackTrace();
}
try {
JSONObject imageInfo = volumeObject.getJSONObject("imageLinks");
new GetBookThumb().execute(imageInfo.getString("smallThumbnail"));
} catch (JSONException jse) {
thumbView.setImageBitmap(null);
jse.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
titleText.setText("NOT FOUND");
authorText.setText("");
descriptionText.setText("");
dateText.setText("");
starLayout.removeAllViews();
ratingCountText.setText("");
thumbView.setImageBitmap(null);
previewBtn.setVisibility(View.GONE);
shelfText.setText("");
}
}
}
private class GetBookThumb extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... thumbURLs) {
try {
URL thumbURL = new URL(thumbURLs[0]);
URLConnection thumbConn = thumbURL.openConnection();
thumbConn.connect();
InputStream thumbIn = thumbConn.getInputStream();
BufferedInputStream thumbBuff = new BufferedInputStream(thumbIn);
thumbImg = BitmapFactory.decodeStream(thumbBuff);
thumbBuff.close();
thumbIn.close();
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
protected void onPostExecute(String result) {
thumbView.setImageBitmap(thumbImg);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void showMaps(View view) {
Intent intent = new Intent(this, MapsActivity.class);
startActivity(intent);
}
//HERE I SAVE THE RETRIEVED DATA
public void saveBook(View view) { //Click on save Book
String title = titleText.getText().toString();
String author = authorText.getText().toString();
String date = dateText.getText().toString();
String rating = ratingCountText.getText().toString();
String shelf = shelfText.getText().toString();
bookDBHelper = new BookDBHelper(context1);
sqLiteDatabase1 = bookDBHelper.getWritableDatabase();
bookDBHelper.addInformations(title, author, date, rating, shelf, sqLiteDatabase1);
Toast.makeText(getBaseContext(), "Data Saved", Toast.LENGTH_LONG).show();
bookDBHelper.close();
}
}
BookDBHelper.java
public class BookDBHelper extends SQLiteOpenHelper{
private static final String DATABASE_BOOKS_NAME = "BookINFO.DB";
private static final int DATABASE_BOOKS_VERS = 2;
private static final String CREATE_QUERY_BOOKS =
"CREATE TABLE "
+ BookContent.NewBookInfo.TABLE_NAME_BOOKS
+"("
+ BookContent.NewBookInfo.BOOK_ID + "INTEGER PRIMARY KEY, "
+ BookContent.NewBookInfo.BOOK_IMAGE +" BLOB, "
+ BookContent.NewBookInfo.BOOK_IMAGE_TAG +" TEXT, "
+ BookContent.NewBookInfo.BOOK_TITLE+" TEXT, "
+ BookContent.NewBookInfo.BOOK_AUTHOR+" TEXT, "
+ BookContent.NewBookInfo.BOOK_DATE+" TEXT, "
+ BookContent.NewBookInfo.BOOK_RATING+" TEXT, "
+ BookContent.NewBookInfo.BOOK_SHELF+" TEXT);";
public BookDBHelper(Context context){
super(context, DATABASE_BOOKS_NAME, null, DATABASE_BOOKS_VERS);
Log.e("DATABASE OPERATIONS", " DATABASE CREATED");
}
#Override
public void onCreate(SQLiteDatabase bookdb) {
bookdb.execSQL(CREATE_QUERY_BOOKS);
Log.e("DATABASE OPERATIONS", " DATABASE CREATED");
}
#Override
public void onUpgrade(SQLiteDatabase bookdb, int oldVersion, int newVersion) {
bookdb.execSQL(" DROP TABLE IS EXISTS " + BookContent.NewBookInfo.TABLE_NAME_BOOKS);
onCreate(bookdb);
}
public void addInformations( String booktitle, String bookauthor, String bookdate, String bookrating, String bookshelf, SQLiteDatabase bookdb)
{
ContentValues contentValues = new ContentValues();
contentValues.put(BookContent.NewBookInfo.BOOK_TITLE, booktitle);
contentValues.put(BookContent.NewBookInfo.BOOK_AUTHOR, bookauthor);
contentValues.put(BookContent.NewBookInfo.BOOK_DATE, bookdate);
contentValues.put(BookContent.NewBookInfo.BOOK_RATING, bookrating);
contentValues.put(BookContent.NewBookInfo.BOOK_SHELF, bookshelf);
bookdb.insert(BookContent.NewBookInfo.TABLE_NAME_BOOKS, null, contentValues);
Log.e("DATABASE OPERATIONS", "ON ROW INSERTED");
}
public Cursor getInformations(SQLiteDatabase bookdb){
Cursor cursor2;
String[] projections = {
BookContent.NewBookInfo.BOOK_TITLE,
BookContent.NewBookInfo.BOOK_AUTHOR,
BookContent.NewBookInfo.BOOK_DATE,
BookContent.NewBookInfo.BOOK_RATING,
BookContent.NewBookInfo.BOOK_SHELF};
cursor2 = bookdb.query(BookContent.NewBookInfo.TABLE_NAME_BOOKS, projections,null, null, null, null, null);
return cursor2;
}
Afterwards the infos will be displayed in a liestview.
BookDataListActivity
public class BookDataListActivity extends Activity {
public ListView booklistView;
private EditText inputSearch = null;
public SQLiteDatabase sqLiteDatabaseBooks = null;
public BookDBHelper bookDBHelper;
public Cursor cursor2;
public BookListDataAdapter bookListDataAdapter;
public final static String EXTRA_MSG1 = "title";
public final static String EXTRA_MSG2 = "author";
public final static String EXTRA_MSG3 = "date";
public final static String EXTRA_MSG4 = "rating";
public final static String EXTRA_MSG5 = "shelf";
public TextView editTextBooktitle;
public TextView editTextBookauthor;
public TextView editTextBookdate;
public TextView editTextBookrating;
public TextView editTextBookshelf;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.book_data_list_layout);
Typeface myTypeface = Typeface.createFromAsset(getAssets(), "Lobster.ttf");
TextView myTextView = (TextView) findViewById(R.id.text_yourbooks);
myTextView.setTypeface(myTypeface);
booklistView = (ListView) findViewById(R.id.book_list_view);
inputSearch = (EditText) findViewById(R.id.search_bar);
bookListDataAdapter = new BookListDataAdapter(getApplicationContext(), R.layout.row_book_layout);
booklistView.setAdapter(bookListDataAdapter);
//onItemClickListener
booklistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getApplicationContext(), BookInfoActivity.class);
editTextBooktitle = (TextView) view.findViewById(R.id.text_book_title);
String book_title = editTextBooktitle.getText().toString();
intent.putExtra(EXTRA_MSG1, book_title);
editTextBookauthor = (TextView) view.findViewById(R.id.text_book_author);
String bookauthor = editTextBookauthor.getText().toString();
intent.putExtra(EXTRA_MSG2, bookauthor);
editTextBookdate = (TextView) view.findViewById(R.id.text_book_date);
String bookdate = editTextBookdate.getText().toString();
intent.putExtra(EXTRA_MSG3, bookdate);
editTextBookrating = (TextView) view.findViewById(R.id.text_book_rating);
String bookrating = editTextBookrating.getText().toString();
intent.putExtra(EXTRA_MSG4, bookrating);
editTextBookshelf = (TextView) view.findViewById(R.id.text_book_shelf);
String bookshelf = editTextBookshelf.getText().toString();
intent.putExtra(EXTRA_MSG5, bookshelf);
startActivity(intent);
}
});
bookDBHelper = new BookDBHelper(getApplicationContext());
sqLiteDatabaseBooks = bookDBHelper.getReadableDatabase();
cursor2 = bookDBHelper.getInformations(sqLiteDatabaseBooks);
if (cursor2.moveToFirst()) {
do {
String booktitle, bookauthor, bookdate, bookrating, bookshelf;
booktitle = cursor2.getString(0);
bookauthor = cursor2.getString(1);
bookdate = cursor2.getString(2);
bookrating = cursor2.getString(3);
bookshelf = cursor2.getString(4);
BookDataProvider bookDataProvider = new BookDataProvider(booktitle, bookauthor, bookdate, bookrating, bookshelf);
bookListDataAdapter.add(bookDataProvider);
} while (cursor2.moveToNext());
}
}
}
And I think you will need the DataAdapter
DataListDataAdapter
public class BookListDataAdapter extends ArrayAdapter implements Filterable{
List booklist = new ArrayList();
public SQLiteDatabase sqLiteDatabaseBooks;
public BookListDataAdapter(Context context,int resource) {
super(context, resource);
}
static class BookLayoutHandler {
TextView BOOKTITLE, BOOKAUTHOR, BOOKDATE, BOOKRATING, BOOKSHELF;
}
#Override
public void add (Object object){
super.add(object);
booklist.add(object);
}
#Override
public int getCount() {
return booklist.size();
}
#Override
public Object getItem(int position) {
return booklist.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row1= convertView;
BookLayoutHandler bookLayoutHandler;
if(row1 == null){
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row1 = layoutInflater.inflate(R.layout.row_book_layout, parent, false);
bookLayoutHandler = new BookLayoutHandler();
bookLayoutHandler.BOOKTITLE = (TextView) row1.findViewById(R.id.text_book_title);
bookLayoutHandler.BOOKAUTHOR = (TextView) row1.findViewById(R.id.text_book_author);
bookLayoutHandler.BOOKDATE = (TextView) row1.findViewById(R.id.text_book_date);
bookLayoutHandler.BOOKRATING = (TextView) row1.findViewById(R.id.text_book_rating);
bookLayoutHandler.BOOKSHELF = (TextView) row1.findViewById(R.id.text_book_shelf);
row1.setTag(bookLayoutHandler);
}else{
bookLayoutHandler = (BookLayoutHandler) row1.getTag();
}
BookDataProvider bookDataProvider = (BookDataProvider) this.getItem(position);
bookLayoutHandler.BOOKTITLE.setText(bookDataProvider.getBooktitle());
bookLayoutHandler.BOOKAUTHOR.setText(bookDataProvider.getBookauthor());
bookLayoutHandler.BOOKDATE.setText(bookDataProvider.getBookdate());
bookLayoutHandler.BOOKRATING.setText(bookDataProvider.getBookrating());
bookLayoutHandler.BOOKSHELF.setText(bookDataProvider.getBookshelf());
return row1;
}
BookDataProvider:
public class BookDataProvider {
private Bitmap bookimage;
private String booktitle;
private String bookauthor;
private String bookdate;
private String bookrating;
private String bookshelf;
public Bitmap getBookimage() {
return bookimage;
}
public void setBookimage(Bitmap bookimage) {
this.bookimage = bookimage;
}
public String getBooktitle() {
return booktitle;
}
public void setBooktitle(String booktitle) {
this.booktitle = booktitle;
}
public String getBookauthor() {
return bookauthor;
}
public void setBookauthor(String bookauthor) {
this.bookauthor = bookauthor;
}
public String getBookdate() {
return bookdate;
}
public void setBookdate(String bookdate) {
this.bookdate = bookdate;
}
public String getBookrating() {
return bookrating;
}
public void setBookrating(String bookrating) {
this.bookrating = bookrating;
}
public String getBookshelf() {
return bookshelf;
}
public void setBookshelf(String bookshelf) {
this.bookshelf = bookshelf;
}
public BookDataProvider ( Bitmap bookimage, String booktitle, String bookauthor, String bookdate, String bookrating, String bookshelf)
{
this.bookimage = bookimage;
this.booktitle = booktitle;
this.bookauthor = bookauthor;
this.bookdate = bookdate;
this.bookrating = bookrating;
this.bookshelf = bookshelf;
}
}
BookContent
public class BookContent {
public static abstract class NewBookInfo{ //Tabllenspalten deklaration
public static final String BOOK_IMAGE = "book_image";
public static final String BOOK_IMAGE_TAG ="image_tag";
public static final String BOOK_TITLE = "book_title";
public static final String BOOK_AUTHOR = "book_author";
public static final String BOOK_DATE = "book_date";
public static final String BOOK_RATING = "book_rating";
public static final String BOOK_SHELF = "book_shelf";
public static final String TABLE_NAME_BOOKS = "book_info";
public static final String BOOK_ID = "_id";
}
}
If I get your question right, you need to convert your image to a blob.
Well, blob is a byte array, so the following code would help you to convert your Bitmap to a byte[]
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 70, thumbImg);
byte[] blob = stream.toByteArray();
You can also get the whole implementation from another question here:
how to store Image as blob in Sqlite & how to retrieve it?
EDIT:
Of course, you have to edit your BookDBHelper.addInformations function and add one additional parameter for your image:
public void addInformations( String booktitle, String bookauthor, String bookdate, String bookrating, String bookshelf, byte[] image, SQLiteDatabase bookdb)
{
ContentValues contentValues = new ContentValues();
contentValues.put(BookContent.NewBookInfo.BOOK_TITLE, booktitle);
contentValues.put(BookContent.NewBookInfo.BOOK_AUTHOR, bookauthor);
contentValues.put(BookContent.NewBookInfo.BOOK_DATE, bookdate);
contentValues.put(BookContent.NewBookInfo.BOOK_RATING, bookrating);
contentValues.put(BookContent.NewBookInfo.BOOK_SHELF, bookshelf);
contentValues.put(YOUR_IMAGE_CONSTANT, image);
bookdb.insert(BookContent.NewBookInfo.TABLE_NAME_BOOKS, null, contentValues);
Log.e("DATABASE OPERATIONS", "ON ROW INSERTED");
}
Now you can save your Book through ScanActivity.saveBook:
public void saveBook(View view) { //Click on save Book
// ...
BitmapDrawable bitmapDrawable = (BitmapDrawable) thumbView.getDrawable();
Bitmap bitmap = bitmapDrawable.getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
byte[] blob = stream.toByteArray();
sqLiteDatabase1 = bookDBHelper.getWritableDatabase();
bookDBHelper.addInformations(title, author, date, rating, shelf, blob, sqLiteDatabase1);
Toast.makeText(getBaseContext(), "Data Saved", Toast.LENGTH_LONG).show();
bookDBHelper.close();
}

How to randomize images in the buttons in android

I am developing a game program where I want to store images in the buttons. I want to randomize the images shown in the buttons when the users play the game again, but I don't know how to randomize the images.
public class MainActivity extends Activity {
public static final String COME_FROM = "come_from";
private int[] id_mc = new int[16];
private Integer[][] img_mc = new Integer [16][2];
private Button[] myMcs = new Button[16];
private int mc_counter = 0;
private int firstid = 0;
private int secondid = 0;
private Boolean mc_isfirst = false;
private int correctcounter = 0;
private TextView tFeedback;
private MediaPlayer mp;
private Boolean b_snd_inc, b_snd_cor;
Random r = new Random();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
Toast.makeText(this, "onCreate", Toast.LENGTH_SHORT).show();
initGame();
}
private void initGame() {
setContentView(R.layout.activity_main);
SharedPreferences settings = getSharedPreferences("memoryPrefs", 0);
b_snd_cor =settings.getBoolean("play_sound_when_correct", true);
b_snd_inc =settings.getBoolean("play_sound_when_incorrect", true);
mc_counter = 0;
firstid = 0;
secondid = 0;
mc_isfirst = false;
correctcounter = 0;
tFeedback = (TextView) findViewById(R.id.mc_feedback);
// setup button listeners
Button startButton = (Button) findViewById(R.id.game_menu);
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startMenu();
}
});
Button settingsButton = (Button) findViewById(R.id.game_settings);
settingsButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startPrefs();
}
});
// fill arrays with resources
id_mc[0] = R.id.mc0;
id_mc[1] = R.id.mc1;
id_mc[2] = R.id.mc2;
id_mc[3] = R.id.mc3;
id_mc[4] = R.id.mc4;
id_mc[5] = R.id.mc5;
id_mc[6] = R.id.mc6;
id_mc[7] = R.id.mc7;
id_mc[8] = R.id.mc8;
id_mc[9] = R.id.mc9;
id_mc[10] = R.id.mc10;
id_mc[11] = R.id.mc11;
id_mc[12] = R.id.mc12;
id_mc[13] = R.id.mc13;
id_mc[14] = R.id.mc14;
id_mc[15] = R.id.mc15;
img_mc[0][0] = R.drawable.back1;
img_mc[0][1] = R.drawable.ic_img1;
img_mc[1][0] = R.drawable.back2;
img_mc[1][1] = R.drawable.ic_img2;
img_mc[2][0] = R.drawable.back3;
img_mc[2][1] = R.drawable.ic_img3;
img_mc[3][0] = R.drawable.back4;
img_mc[3][1] = R.drawable.ic_img4;
img_mc[4][0] = R.drawable.back5;
img_mc[4][1] = R.drawable.ic_img5;
img_mc[5][0] = R.drawable.back6;
img_mc[5][1] = R.drawable.ic_img6;
img_mc[6][0] = R.drawable.back7;
img_mc[6][1] = R.drawable.ic_img7;
img_mc[7][0] = R.drawable.back8;
img_mc[7][1] = R.drawable.ic_img8;
img_mc[8][0] = R.drawable.back1;
img_mc[8][1] = R.drawable.ic_img1;
img_mc[9][0] = R.drawable.back2;
img_mc[9][1] = R.drawable.ic_img2;
img_mc[10][0] = R.drawable.back3;
img_mc[10][1] = R.drawable.ic_img3;
img_mc[11][0] = R.drawable.back4;
img_mc[11][1] = R.drawable.ic_img4;
img_mc[12][0] = R.drawable.back5;
img_mc[12][1] = R.drawable.ic_img5;
img_mc[13][0] = R.drawable.back6;
img_mc[13][1] = R.drawable.ic_img6;
img_mc[14][0] = R.drawable.back7;
img_mc[14][1] = R.drawable.ic_img7;
img_mc[15][0] = R.drawable.back8;
img_mc[15][1] = R.drawable.ic_img8;
//Collections.shuffle(Arrays.asList(img_mc));
for (int i = 0; i < 16; i++) {
try{
myMcs[i] = (Button) findViewById(id_mc[i]);
myMcs[i].setBackgroundResource(img_mc[i][0]);
myMcs[i].setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
int i = 0;
for (int n = 0; n < 16; n++) {
if (id_mc[n] == view.getId())
i = n;
}
doClickAction(view, i);
}
});
}catch(Exception e)
{
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}}
}
private void doClickAction(View v, int i)
{
v.setBackgroundResource(img_mc[i][1]);
mc_isfirst = !mc_isfirst;
// disable all buttons
for (Button b : myMcs) {
b.setEnabled(false);
}
if (mc_isfirst) {
// turning the first card
firstid = i;
// re enable all except this one
for (Button b : myMcs) {
if (b.getId() != firstid) {
b.setEnabled(true);
}
}
} else {
// turning the second card
secondid = i;
doPlayMove();
}
}
private void doPlayMove() {
mc_counter++;
if (img_mc[firstid][1] - img_mc[secondid][1] == 0) {
//correct
if (b_snd_cor) playSound(R.raw.correct);
waiting(200);
myMcs[firstid].setVisibility(View.INVISIBLE);
myMcs[secondid].setVisibility(View.INVISIBLE);
correctcounter++;
} else {
//incorrect
if (b_snd_inc) playSound(R.raw.incorrect);
waiting(400);
}
// reenable and turn cards back
for (Button b : myMcs) {
if (b.getVisibility() != View.INVISIBLE) {
b.setEnabled(true);
b.setBackgroundResource(R.drawable.memory_back);
for (int i = 0; i < 16; i++) {
myMcs[i].setBackgroundResource(img_mc[i][0]);
}
}
}
tFeedback.setText("" + correctcounter + " / " + mc_counter);
if (correctcounter > 7) {
Intent iSc = new Intent(getApplicationContext(), Scoreboard.class);
iSc.putExtra("com.gertrietveld.memorygame.SCORE", mc_counter);
startActivity(iSc);
finish();
}
}
public void playSound(int sound) {
mp = MediaPlayer.create(this, sound);
mp.setVolume((float).5,(float).5);
mp.start();
mp.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
}
public static void waiting(int n) {
long t0, t1;
t0 = System.currentTimeMillis();
do {
t1 = System.currentTimeMillis();
} while ((t1 - t0) < (n));
}
private void startMenu() {
Intent launchMenu = new Intent(this, MenuScreen.class);
launchMenu.putExtra(COME_FROM,"PlayGame");
startActivity(launchMenu);
}
private void startPrefs() {
Intent launchPrefs = new Intent(this, Setting.class);
startActivity(launchPrefs);
}
////////////////////////////////
#Override
protected void onRestart() {
super.onRestart();
//String sender = getIntent().getExtras().getString("SENDER");
//initGame();
Toast.makeText(this, "onRestart-sender is " , Toast.LENGTH_SHORT).show();
}
#Override
protected void onResume() {
super.onResume();
SharedPreferences settings = getSharedPreferences("memoryPrefs", 0);
b_snd_cor =settings.getBoolean("play_sound_when_correct", true);
b_snd_inc =settings.getBoolean("play_sound_when_incorrect", true);
Toast.makeText(this, "onResume", Toast.LENGTH_SHORT).show();
}
////////////////////////////////
}
You had the Collections.shuffle() part right, you just need to get the randomized list back into your array:
private Integer[][] img_mc = new Integer [16][2];
...
List<Integer[]> img_mc_list = new ArrayList<Integer[]>();
for (Integer[] img : img_mc) {
img_mc_list.add(img);
}
Collections.shuffle(img_mc_list);
img_mc_list.toArray(img_mc);
Or use this:
private void randomize(Integer[][] array) {
int index;
Integer[] temp;
Random random = new Random();
for (int i = array.length - 1; i > 0; i--) {
index = random.nextInt(i + 1);
temp = array[index];
array[index] = array[i];
array[i] = temp;
}
}

Activity State not saved

I want to save my Activity state while I swipe between activities but I cannot. Some things are saved and the others dont. I think it has to do somehow with the gestureListener I'm impementing but I'm not sure.
When I swipe to a different activity and then back to this one - the AsyncTask is still running and the Handler is still updating the GUI, however, the views I have displaying in this activity and the buttons are all in their initial configuration.
what am I doing wrong?
public class Main extends Activity implements OnClickListener,
SimpleGestureListener {
/** Called when the activity is first created. */
static String checkedIN = "";
private int hoursSum;
private int minutesSum;
static int dayIs;
static String madeSoFar = "";
static int hoursCount = 0;
static String formattedSeconds = "";
static String formattedMinutes = "";
public static NumberFormat formatter = new DecimalFormat("#0.00");
static boolean killcheck = false;
static String time = "";
static Handler mHandler;
private boolean clicked = false;
private boolean wasShift = false;
static String startString;
static String finishString;
private SimpleGestureFilter detector;
private Typeface tf, tf2, roboto;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
// **************** Set Fonts **************
roboto = Typeface.createFromAsset(getAssets(), "fonts/robotothin.ttf");
tf = Typeface.createFromAsset(getAssets(), "fonts/Advert.ttf");
tf2 = Typeface.createFromAsset(getAssets(), "fonts/passion.ttf");
// **************** Gesture implementation ************
detector = new SimpleGestureFilter(this, this);
// **************** Date and Time Objects *************
final Date date = new Date();
final Date today = Calendar.getInstance().getTime();
DateFormat DF = new SimpleDateFormat("dd/MM/yyyy");
final String DateInString = DF.format(today);
String myString = DateFormat.getDateInstance().format(date);
final TextView dateDisplay = (TextView) findViewById(R.id.dateDisplay);
dateDisplay.setText(myString);
final DBAdapter DB = new DBAdapter(this);
// ************* Apply custom fonts ***************
TextView Title = (TextView) findViewById(R.id.textView2);
Title.setTypeface(tf);
final TextView Author = (TextView) findViewById(R.id.textView3);
Author.setTypeface(roboto);
TextView Current = (TextView) findViewById(R.id.textView1);
Current.setTypeface(roboto);
DigitalClock DG = (DigitalClock) findViewById(R.id.digitalClock1);
DG.setTypeface(roboto);
TextView dater = (TextView) findViewById(R.id.date);
dater.setTypeface(roboto);
TextView dateDisp = (TextView) findViewById(R.id.dateDisplay);
dateDisp.setTypeface(roboto);
CheckedTextView CV = (CheckedTextView) findViewById(R.id.radioButton1);
CV.setTypeface(roboto);
// *************************************************//
final Button checkIn = (Button) findViewById(R.id.CheckIn);
checkIn.setTypeface(roboto);
CheckedTextView check = (CheckedTextView) findViewById(R.id.radioButton1);
Boolean enable = false;
check.setEnabled(enable);
mHandler = new Handler() {
public void handleMessage(Message msg) {
time = "Time: " + hoursCount + ":" + formattedMinutes + ":"
+ formattedSeconds + " Money: " + madeSoFar;
Author.setText(time);
}
};
// **************** Click Listener for first Check In Button
checkIn.setOnClickListener(new OnClickListener() {
int startHours;
int startMinutes;
int finishHours;
int finishMinutes;
#Override
public void onClick(View v) {
// Check Out
if (clicked == true) {
killcheck = true;
checkedIN = "Check In";
checkIn.setText(checkedIN);
finishHours = Utility.getHoursTime();
finishMinutes = Utility.getMinutesTime();
finishString = Integer.toString(Utility.getHoursTime())
+ ":" + Integer.toString(Utility.getMinutesTime())
+ " -";
clicked = false;
wasShift = true;
hoursSum = finishHours - startHours;
minutesSum = finishMinutes - startMinutes;
// Check In
} else if (clicked == false) {
checkedIN = "Check Out";
checkIn.setText(checkedIN);
killcheck = false;
new ShiftProgress().execute();
startHours = Utility.getHoursTime();
startMinutes = Utility.getMinutesTime();
startString = Integer.toString(Utility.getHoursTime())
+ ":" + Integer.toString(Utility.getMinutesTime())
+ " -";
String s = "In Shift ";
CheckedTextView radio = (CheckedTextView) findViewById(R.id.radioButton1);
radio.setText(s);
clicked = true;
}
}
});
Button addShift = (Button) findViewById(R.id.addShift);
addShift.setTypeface(tf2);
// **************** On click listener for adding a shift
addShift.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (wasShift == true) {
changeDateToString(DateInString);
DB.open();
final Cursor cursor = DB.getAllShifts();
startManagingCursor(cursor);
cursor.moveToLast();
int count = cursor.getPosition();
final int position = count + 2;
cursor.moveToNext();
GregorianCalendar GC = new GregorianCalendar();
DB.addToDBTotal(DateInString, "Money: " + madeSoFar,
hoursSum, minutesSum,
Utility.getDay(GC.get(Calendar.DAY_OF_WEEK)),
position, startString, finishString);
DBAdapter.close();
wasShift = false;
printAny(getApplicationContext(), "Added to Shifts",
Toast.LENGTH_SHORT);
} else {
printAny(getApplicationContext(), "Please Check In First", Toast.LENGTH_SHORT);
}
}
});
}
// **************** METHOD DECLERATIONS ****
public void viewShifts() {
Intent myIntent = new Intent(Main.this, Shifts.class);
startActivity(myIntent);
}
public void changeDateToString(String s) {
Utility.INSTANCE.setDate(s);
}
public void changeDurationToString(String s) {
Utility.INSTANCE.setDuration(s);
}
public void printAny(Context c, CharSequence s, int i) {
Context context = c;
CharSequence text = s;
final int duration = i;
Toast toast = Toast.makeText(context, text, duration);
toast.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER, 0, 0);
toast.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.exit:
System.exit(1);
DBAdapter.close();
return true;
case R.id.view:
viewShifts();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
#Override
public void onSwipe(int direction) {
Intent intent = new Intent();
switch (direction) {
case SimpleGestureFilter.SWIPE_RIGHT:
intent.setClass(this, Shifts.class);
startActivity(intent);
break;
case SimpleGestureFilter.SWIPE_LEFT:
intent.setClass(this, Shifts.class);
startActivity(intent);
break;
}
}
#Override
public boolean dispatchTouchEvent(MotionEvent me) {
this.detector.onTouchEvent(me);
return super.dispatchTouchEvent(me);
}
#Override
public void onDoubleTap() {
// TODO Auto-generated method stub
}
public class ShiftProgress extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
int count = 0;
int seconds = 0;
int minutesTime = 0;
int minutesCount = 1;
for (;;) {
if (seconds % 60 == 0) {
minutesTime = count / 60;
seconds = 0;
}
if (seconds < 10) {
formattedSeconds = String.format("%02d", seconds);
}
else if (seconds >= 10) {
formattedSeconds = String.valueOf(seconds);
}
if (minutesTime < 10) {
formattedMinutes = String.format("%02d", minutesTime);
}
else if (minutesTime >= 10) {
formattedMinutes = String.valueOf(minutesTime);
}
if (minutesTime % 60 == 0) {
hoursCount = minutesCount / 60;
minutesTime = 0;
}
double sal = 40;
double SEC = 3600;
double salper = count * (sal / SEC);
madeSoFar = String.valueOf(formatter.format(salper));
try {
mHandler.obtainMessage(1).sendToTarget();
Thread.sleep(1000);
seconds++;
count++;
} catch (InterruptedException e) {
e.printStackTrace();
}
if (killcheck) {
break;
}
}
// int length = count /360;
return null;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(Long result) {
}
}
#Override
public void onSaveInstanceState() {
// TODO Auto-generated method stub
Toast.makeText(this, "Activity state saved", Toast.LENGTH_LONG);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
checkedIN = savedInstanceState.getString("checkIN");
clicked = savedInstanceState.getBoolean("button");
Toast.makeText(this, "Activity state Restored", Toast.LENGTH_LONG);
}
#Override
public void onPause(Bundle b) {
// TODO Auto-generated method stub
b.putString("checkIN", checkedIN);
b.putBoolean("button", clicked);
Toast.makeText(this, "Activity state saved", Toast.LENGTH_LONG);
super.onPause();
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putString("checkIN", checkedIN);
outState.putBoolean("button", clicked);
Toast.makeText(this, "Activity state saved", Toast.LENGTH_LONG);
// etc.
super.onSaveInstanceState(outState);
}
#Override
protected void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Activity is getting killed", Toast.LENGTH_LONG)
.show();
}
}
You should not keep your Async task running in the background when your activity is send to the background. Your activity can be quit at any time so that you wouldn't have a reference to your activity anymore.
Regarding the preservation of state you could have a look at Activity.onRetainNonConfigurationInstance()

Categories

Resources