I have seen a decent amount of methods to add a numerical value to an int integer value using intent(). Mine however is not working so well. Does anyone have any advice? I am sending an integer value, via a button, from a separate activity using theintent() method. This value should add 1 to the activity when the button is pressed. Here is what I have so far:
public class GameEmulator extends Activity{
//Creating two static values to pass strings from SelectPlayer classes
public final static String value = "EMPTY_VALUE";
public final static String value2 = "EMPTY_VALUE2";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
//Button created to go back to AddPlayer activity
Button addplayer1 = findViewById(R.id.button9);
addplayer1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(GameEmulator.this, AddPlayer.class);
startActivity(i);
}
});
Button viewScores = findViewById(R.id.viewScore);
viewScores.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(GameEmulator.this, MainActivity.class);
startActivity(intent);
}
});
//Button for player one winning
Button winButtonOne = findViewById(R.id.button7);
winButtonOne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int scored = 1;
Intent intent = new Intent(GameEmulator.this, Scoreboard.class);
intent.putExtra("MY_KEY", scored);
startActivity(intent);
}
});
TextView textView = findViewById(R.id.name1);
TextView textview2 = findViewById(R.id.name2);
//setting value retrieved from SleectPlayer and Displaying it in textView
Intent intent = getIntent();
String extra = intent.getStringExtra(value);
textView.setText(extra);
//setting value retrieved from SleectPlayer2 and Displaying it in textView2
Intent in = getIntent();
String extra1 = in.getStringExtra(value2);
textview2.setText(extra1);
}
}
public class Scoreboard extends Activity{
public static ArrayAdapter<String> adapter2;
public static ArrayAdapter<String> adapter3;
public static ArrayList<String> list2 = new ArrayList<>();
public static ArrayList<String> list3 = new ArrayList<>();
ListView selectView3;
ListView selectView4;
public static int losses1 = 0;
public static int ties1 = 0;
public static int losses2 = 0;
public static int ties2 = 0;
public final static String value2 = "EMPTY_VALUE2";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.scoreboard);
selectView3 = findViewById(R.id.selectview3);
selectView3.setVisibility(View.VISIBLE);
selectView4 = findViewById(R.id.selectview4);
selectView4.setVisibility(View.VISIBLE);
//Using adapter for ListView menu
adapter2 = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, list2);
selectView3.setAdapter(adapter2);
//Using intent to retrieve string from AddPlayer Activity
Intent i = getIntent();
int score = getIntent().getIntExtra("MY_KEY", 1);
String data = i.getStringExtra("text_key");
if(data != null){
list2.add("Player 1"+"\n"+"Name: "+data+"\n"+"Wins: "+ score +"\n"+"Losses: "+ losses1+"\n"+"Ties: "+ ties1);
}
if(data != ""){
changeList();
}
adapter3 = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, list3);
selectView4.setAdapter(adapter3);
Intent intent = getIntent();
String extra= intent.getStringExtra(value2);
if(extra != null) {
list3.add("Player 2" + "\n" + "Name: " + extra + "\n" + "Wins: " + score + "\n" + "Losses: " + losses2 + "\n" + "Ties: " + ties2);
}
if(data != ""){
changeList();
}
}
public void changeList()
{
adapter2.notifyDataSetChanged();
}
}
This line:
String data = i.getStringExtra("text_key");
makes data = null because you did not put in the original intent an extra value with key "text_key"
So this code:
list2.add("Player 1"+"\n"+"Name: "+data+"\n"+"Wins: "+ score +"\n"+"Losses: "+ losses1+"\n"+"Ties: "+ ties1);
is never executed
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();
}
I have an app in which I have to combine parts of clothes. To understand me better I have given a screenshot below. The thing is, that i am having problems on how to get these images and save them in my database. Of course i faced errors.
public class ViewOutfit extends Activity {
private DatabaseHandler handler;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_outfit);
Intent i = getIntent();
final ImageView im1 = (ImageView) findViewById(R.id.im1);
im1.setImageBitmap(BitmapFactory.decodeFile(i.getStringExtra("image1")));
im1.toString();
final ImageView im2 = (ImageView) findViewById(R.id.im2);
im2.setImageBitmap(BitmapFactory.decodeFile(i.getStringExtra("image2")));
im2.toString();
final ImageView im3 = (ImageView)findViewById(R.id.im3);
im3.setImageBitmap(BitmapFactory.decodeFile(i.getStringExtra("image3")));
im3.toString();
final ImageView im4 = (ImageView)findViewById(R.id.im4);
im4.setImageBitmap(BitmapFactory.decodeFile(i.getStringExtra("image4")));
im4.toString();
final ImageView im5 = (ImageView)findViewById(R.id.im5);
im5.setImageBitmap(BitmapFactory.decodeFile(i.getStringExtra("image5")));
im5.toString();
final ImageView im6 = (ImageView)findViewById(R.id.im6);
im6.setImageBitmap(BitmapFactory.decodeFile(i.getStringExtra("image6")));
im6.toString();
ImageButton btn_save_outfit = (ImageButton)findViewById(R.id.btn_combine);
btn_save_outfit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
im1.getDrawable().toString();
im2.getDrawable().toString();
im3.getDrawable().toString();
im4.getDrawable().toString();
im5.getDrawable().toString();
im6.getDrawable().toString();
Outfits outfits = new Outfits();
outfits.setImage1(String.valueOf(im1));
outfits.setImage2(String.valueOf(im2));
outfits.setImage3(String.valueOf(im3));
outfits.setImage4(String.valueOf(im4));
outfits.setImage5(String.valueOf(im5));
outfits.setImage6(String.valueOf(im6));
Boolean added = handler.addOutfit(outfits);
if(added){
Toast.makeText(getApplicationContext() , "Outfit added." , Toast.LENGTH_LONG).show();
String log = "Id: "+ outfits.getID()+" ,Image1: " + outfits.getImage1() + " ,Image2: " + outfits.getImage2()
+ ",Image3:" + outfits.getImage3() + ",Image4:" + outfits.getImage5() + ",Image6:" +outfits.getImage6();
Log.d("Image1: ", log);
}else{
Toast.makeText(getApplicationContext(), "Outfit not added. Please try again", Toast.LENGTH_LONG).show();
}
}});
}
I have done the following things in my program:
I am generating some Buttons programmatically in my MenuItemsActivity class. I have a Listview in the xml of the MenuItemsActivity class.
When I click on the button the appropriate contents get loaded in the Listview. I just refresh the activity i.e I am using the same Listview to load different contents based on the button which is clicked.
I want to do the following:
When the Button is clicked I want to change the background of the button to 'blue_tab` and maintain that same color when the same activity reloads. Can anyone guide me step by step what to do, as I am a newbie to Android.
i = getIntent();
String Salad=i.getStringExtra("Salad");
String cat_name_from_fragment=i.getStringExtra("category name");
final ListView salad_list = (ListView) findViewById(R.id.salads);
category = new ArrayList<HashMap<String, String>>();
items = new ArrayList<HashMap<String, String>>();
db = new DbHelper(MenuItemsActivity.this);
category.clear();
if (i.getStringExtra("category name") != null) {
String getcategory = i.getStringExtra("category name").toString();
items = db.retrieve_item_details(getcategory);
Log.i("sub items", "" + items);
}
else if(cat_name_from_fragment!=null)
{
items = db.retrieve_item_details(cat_name_from_fragment);
}
else
{
items = db.retrieve_item_details("Salads");
}
category = db.retrieve_category_name();
count = category.size();
Log.i("Sqlite database values", "" + count + " " + category);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
LinearLayout l1 = (LinearLayout) findViewById(R.id.tableRow1);
int i = 0;
for (HashMap<String, String> map : category)
for (Entry<String, String> mapEntry : map.entrySet()) {
String key = mapEntry.getKey();
String value = mapEntry.getValue();
TextView tv2 = new TextView(this);
tv2.setLayoutParams(new LinearLayout.LayoutParams(40, 90));
Log.i("map", "" + value);
final Button tv1 = new Button(this);
tv1.setId(i);
tv1.setText(value);
tv1.setTextSize(35);
tv1.setTextColor(Color.parseColor("#1569C7"));
tv1.setGravity(Gravity.CENTER);
tv1.setBackgroundDrawable(getResources().getDrawable(R.drawable.popup));
tv1.setLayoutParams(new LinearLayout.LayoutParams(300,90));
tv1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String text = tv1.getText().toString();
Log.e("text message", "" + text);
tv1.setBackgroundDrawable(getResources().getDrawable(R.drawable.blue_tab));
Toast.makeText(MenuItemsActivity.this, "clicked", 1000)
.show();
Intent i = new Intent(MenuItemsActivity.this,
MenuItemsActivity.class);
i.putExtra("category name", "" + text);
finish();
startActivity(i);
}
});
/*TextView tv2 = new TextView(this);
tv2.setText(" ");
tv2.setTextSize(10);
tv2.setGravity(Gravity.CENTER);*/
l1.addView(tv1);
l1.addView(tv2);
i++;
Log.e("i count ", "" + i);
}
final int imageArra[] = { R.drawable.leftbar_logo ,R.drawable.leftbar_logo};
ListAdapter k = new SimpleAdapter(MenuItemsActivity.this, items,
R.layout.menulist, new String[] { "Item_Name", "Desc",
"Currency", "Price","url","veggie","cat" }, new int[] { R.id.cat_name,
R.id.textView1, R.id.textView2, R.id.textView3,R.id.url,R.id.veggie,R.id.Category}) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final View v = super.getView(position, convertView, parent);
final ImageView im=(ImageView)v.findViewById(R.id.imageView1);
TextView url=(TextView)v.findViewById(R.id.url);
TextView veg=(TextView)v.findViewById(R.id.veggie);
String vegg=veg.getText().toString();
ImageView imagevegs=(ImageView)v.findViewById(R.id.veggies);
Log.i("veggie",""+vegg);
if(vegg.compareToIgnoreCase("Veg")==0)
{
imagevegs.setImageResource(R.drawable.veg);
imagevegs.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
}
else
{imagevegs.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imagevegs.setImageResource(R.drawable.non);
}
final String urls="http://166.62.17.208/"+url.getText().toString();
Log.i("urls",""+urls);
imageLoader.DisplayImage(urls,im);
//return super.getView(position, convertView, parent);
return v;
}
};
salad_list.setAdapter(k);
You can use PreferenceManager to save data and use it when the app is reloaded/restarted
sample:
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String text = tv1.getText().toString();
Log.e("text message", "" + text);
if(PreferenceManager.getDefaultSharedPreferences(MenuItemsActivity.this).getString("button", "").length != 0)
tv1.setBackgroundDrawable(getResources().getDrawable(R.drawable.blue_tab));
else
{
Editor editor = PreferenceManager.getDefaultSharedPreferences(MenuItemsActivity.this).edit();
editor.putString("button", "1");
editor.commit();
tv1.setBackgroundDrawable(getResources().getDrawable(R.drawable.blue_tab));
}
Toast.makeText(MenuItemsActivity.this, "clicked", 1000)
.show();
Intent i = new Intent(MenuItemsActivity.this,
MenuItemsActivity.class);
i.putExtra("category name", "" + text);
finish();
startActivity(i);
}
Hello, my old code is working, but the problem is that when i am clicking tablerow it call another activty, but it not set that table row data but it setting last array data to that activity.
Means it set the last array value to next screen activity.
for ( j = 0; j < dataListfeture.size(); j++)
{
HashMap<String, String> hm = new HashMap<String, String>();
hm = dataListfeture.get(j);
final TableRow tblrow = new TableRow(MainScreen.this);
final View rowView = inflater.inflate(R.layout.featuredrow, null);
tblrow.setId(j);
tblrow.getId();
featuredName = (TextView) rowView.findViewById(R.id.xxName);
featuredDistance = (TextView) rowView.findViewById(R.id.xxDistance);
featuredVeneType = (TextView) rowView.findViewById(R.id.xxVeneType);
featuredPhone = (TextView) rowView.findViewById(R.id.xxPhone);
featuredAddress = (TextView) rowView.findViewById(R.id.xxAddress);
Drawable image = ImageOperations(MainScreen.this, hm.get("url"), "image.jpg");
featuredImage = (ImageView) rowView.findViewById(R.id.xxdImage);
featuredImage.setImageDrawable(image);
featuredName.setText("" + hm.get("name"));
featuredDistance.setText("" + hm.get("distance") + " mi");
featuredVeneType.setText("" + hm.get("venuetype"));
featuredPhone.setText("" + hm.get("phonenumber"));
featuredAddress.setText("" + hm.get("address"));
mapnamelist = hm.get("name");
mapvenuelist = hm.get("venuetype");
mapothervenuelist = hm.get("othervenuetype");
mapaddresslist= hm.get("address");
mapcitylist= hm.get("city");
mapstatelist= hm.get("state");
tblrow.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
final ProgressDialog progDailog = ProgressDialog.show(MainScreen.this, null, "Loading ....", true);
final Handler handler = new Handler()
{
public void handleMessage(Message msg)
{
System.out.println("search");
Intent myIntent = new Intent(MainScreen.this, xxxxscreen.class);
startActivity(myIntent);
MainScreen.this.finish();
progDailog.dismiss();
}
};
new Thread()
{
public void run()
{
try
{
System.out.println();
handler.sendEmptyMessage(1);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}.start();
}
});
Create an int array of id say array_id[] and after setting id to table row add that id to array_id[] also like
tblrow.setId(j);
array_id[j] = j;
And in onClick method do this:
for(int i = 0;i< array_id.length;i++)
{
TableRow tbl_row = (TableRow) findViewById(i);
if(v.getId() == array_id[i])
{
/** Perform your Operations */
}
}