how can save last Selected or Captured image in imageView? so when user close program and come back again not need to set or take image again?
xml fle:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="5dp" >
<Button
android:id="#+id/btnSelectPhoto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select Photo" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp" >
<ImageView
android:id="#+id/viewImage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="#drawable/camera" />
</LinearLayout>
</LinearLayout>
java file :
public class MainActivity extends Activity {
ImageView viewImage;
Button b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b=(Button)findViewById(R.id.btnSelectPhoto);
viewImage=(ImageView)findViewById(R.id.viewImage);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds options to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo"))
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
}
else if (options[item].equals("Choose from Gallery"))
{
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
viewImage.setImageBitmap(bitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
f.delete();
OutputStream outFile = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Log.w("path of image from gallery......******************.........", picturePath+"");
viewImage.setImageBitmap(thumbnail);
}
}
}
}
this code coped from :
http://www.c-sharpcorner.com/UploadFile/e14021/capture-image-from-camera-and-selecting-image-from-gallery-o/
Thank you very mach
You could save the image(path) as a preference in the OnPause() and load it again in OnResume(). With that path, you can set the image in ImageView again. So it's 2 steps.
More info on the lifecylce of an Android application: http://developer.android.com/training/basics/activity-lifecycle/pausing.html
Related
enter image description hereI already create a report layout in XML in android studio. I need to transform the layout to PDF format after clicking on Generate button on the layout. Are there any possibilities to make it possible? Thank you in advance!
I want to convert that data form the layout into pdf in that exact table
For generating pdf:
-> Add permission for reading and writing in the External Storage in manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
-> On click of generate pdf button, Check Permissions are granted or not.
Try this code on click of button:
/*check read/write storage permission is granted or not*/
if(checkPermissionGranted()){
convertToPdf();
}else{
requestPermission();
}
checkPermissionGranted() method:
private boolean checkPermissionGranted(){
if((ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
&& (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)) {
// Permission has already been granted
return true;
} else {
return false;
}
}
requestPermission() method:
private void requestPermission(){
ActivityCompat.requestPermissions(LayoutToPdfActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
}
Override onActivityResult metod:
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1) {
if (resultCode == Activity.RESULT_OK) {
convertToPdf();
}else{
requestPermission();
}
}
}
convertToPdf() method:
private void convertToPdf(){
PdfGenerator pdfGenerator = new PdfGenerator(LayoutToPdfActivity.this);
// llLayoutToPdfMain is variable of that view which convert to PDF
Bitmap bitmap = pdfGenerator.getViewScreenShot(llLayoutToPdfMain);
pdfGenerator.saveImageToPDF(llLayoutToPdfMain, bitmap);
}
PdfGenerator Class:
public class PdfGenerator {
private static String TAG= PdfGenerator.class.getSimpleName();
private File mFile;
private Context mContext;
public PdfGenerator(Context context) {
this.mContext = context;
}
/*save image to pdf*/
public void saveImageToPDF(View title, Bitmap bitmap) {
File path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOCUMENTS);
if(!path.exists()) {
path.mkdirs();
}
try {
mFile = new File(path + "/", System.currentTimeMillis() + ".pdf");
if (!mFile.exists()) {
int height = bitmap.getHeight();
PdfDocument document = new PdfDocument();
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(bitmap.getWidth(), height, 1).create();
PdfDocument.Page page = document.startPage(pageInfo);
Canvas canvas = page.getCanvas();
title.draw(canvas);
canvas.drawBitmap(bitmap, null, new Rect(0, bitmap.getHeight(), bitmap.getWidth(), bitmap.getHeight()), null);
document.finishPage(page);
try {
mFile.createNewFile();
OutputStream out = new FileOutputStream(mFile);
document.writeTo(out);
document.close();
out.close();
Log.e(TAG,"Pdf Saved at:"+mFile.getAbsolutePath());
Toast.makeText(mContext,"Pdf Saved at:"+mFile.getAbsolutePath(),Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/*method for generating bitmap from LinearLayout, RelativeLayout etc.*/
public Bitmap getViewScreenShot(View view)
{
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bm = view.getDrawingCache();
return bm;
}
/*method for generating bitmap from ScrollView, NestedScrollView*/
public Bitmap getScrollViewScreenShot(ScrollView nestedScrollView)
{
int totalHeight = nestedScrollView.getChildAt(0).getHeight();
int totalWidth = nestedScrollView.getChildAt(0).getWidth();
return getBitmapFromView(nestedScrollView,totalHeight,totalWidth);
}
public Bitmap getBitmapFromView(View view, int totalHeight, int totalWidth) {
Bitmap returnedBitmap = Bitmap.createBitmap(totalWidth,totalHeight , Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(returnedBitmap);
Drawable bgDrawable = view.getBackground();
if (bgDrawable != null)
bgDrawable.draw(canvas);
else
canvas.drawColor(Color.WHITE);
view.draw(canvas);
return returnedBitmap;
}
}
Edit
Please follow below xml code snippet for layout designing:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
tools:context=".views.activities.LayoutToPdfActivity">
<androidx.core.widget.NestedScrollView
android:id="#+id/nestedLayoutToPdf"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/btnGeneratePdf">
<LinearLayout
android:id="#+id/llLayoutToPdfMain"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center">
<TableLayout
android:id="#+id/tableLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</TableLayout>
<TableLayout
android:id="#+id/tableLayout2"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</TableLayout>
</LinearLayout>
</androidx.core.widget.NestedScrollView>
<Button
android:id="#+id/btnGeneratePdf"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Generate Pdf"
android:layout_margin="20dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
-> Change in convertToPdf() method
private void convertToPdf() {
PdfGenerator pdfGenerator = new PdfGenerator(LayoutToPdfActivity.this);
Bitmap bitmap = pdfGenerator.getScrollViewScreenShot(nestedLayoutToPdf);
pdfGenerator.saveImageToPDF(llLayoutToPdfMain, bitmap);
}
Note - Please change layout according to your requirement and Change param type to NestedScrollView in getScrollViewScreenShot() method under PdfGenerator Class.
For dynamically adding rows in tableview, check this link
I'm hoping someone can help me. I have created a Sudoku app. I have a grid view that shows string text from a list view. I have a problem with my layout of the Grid View on my phone and tablet; , see 1st and 2nd screens below .
What I'm trying to do is set the screen, so the grid display neatly just above the numbers 1 to 5. Ideally I'd like it to render appropriately on tablet and phone.
On a Phone the last row of the sudoku grid showing underneath the first set of button button See firstImage. Whereas on a Tablet there is a huge gap between the gridvview and the Buttons
What I have I tried so far:
I tried android:layout_above btn1. But that chopped off the last row of the sudoku grid and I had to drag the grid up and down to see the last row on a phone. It also caused the app to crash of a phone. Not good.
I tried putting a frame layout inside the relative layout and putting the gridview inside of that. But that had the also chopped off the last row of the sudoku grid as per layout_above.
Really what I'd like to do is, on a phone I would like to remove or reduce the padding above and below each number in each cell in the grid view. As the cell padding makes each cell in the grid 2 - 3 times bigger than it needs to be. This is a problem on a 5" mobile phone screen. I have tried the following and none of them worked.
How do I get rid of unwanted padding in a Listview row
android:gravity - Made no Difference
How to avoid space between imageview and gridview in linearlayout
listSelector=”#null” - Made no difference
Removing the extra padding in a GridView in android
stretchMode(0); - Everything disappeared.
How do I get rid of unwanted padding in a Listview row
view.setMinimumHeight(0); - Made no difference.
I also tried view.setPadding(); it was useful in that the padding on the left hand side was removed, but it didn't remove the papdding at the top or bottom.
view.setPadding(dpToPx(0, parent), 0, 0, 0);
I am at a loss at this stage about how to move this forward and am worried that trying all these different things is making me more confused. If someone could point me in the correct direction I'd be very grateful. Code is shown below.
content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.admin1.sudoku.MainActivity"
android:background="#663399"
tools:showIn="#layout/activity_main">
<Button
android:id="#+id/btn1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/btn1Label"
android:layout_above="#+id/btn6"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignBottom="#+id/btn2"
/>
<Button
android:id="#+id/btn2"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/btn2Label"
android:layout_above="#+id/btn7"
android:layout_toLeftOf="#+id/btn8"
android:layout_toStartOf="#+id/btn8" />
<Button
android:id="#+id/btn3"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/btn3Label"
android:layout_alignTop="#+id/btn2"
android:layout_toRightOf="#+id/btn2"
android:layout_toEndOf="#+id/btn2" />
<Button
android:id="#+id/btn4"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/btn4Label"
android:layout_alignTop="#+id/btn3"
android:layout_toRightOf="#+id/btn3"
android:layout_toEndOf="#+id/btn3" />
<Button
android:id="#+id/btn5"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/btn5Label"
android:layout_alignTop="#+id/btn4"
android:layout_toRightOf="#+id/btn4"
android:layout_toEndOf="#+id/btn4" />
<Button
android:id="#+id/btn6"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/btn6Label"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:id="#+id/btn7"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/btn7Label"
android:layout_alignParentBottom="true"
android:layout_toRightOf="#+id/btn6"
android:layout_toEndOf="#+id/btn6" />
<Button
android:id="#+id/btn8"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/btn8Label"
android:layout_alignParentBottom="true"
android:layout_toRightOf="#+id/btn7"
android:layout_toEndOf="#+id/btn7" />
<Button
android:id="#+id/btn9"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/btn9Label"
android:layout_alignParentBottom="true"
android:layout_toRightOf="#+id/btn3"
android:layout_toEndOf="#+id/btn3" />
<Button
android:id="#+id/btn0"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/btn0Label"
android:layout_alignParentBottom="true"
android:layout_toRightOf="#+id/btn9"
android:layout_toEndOf="#+id/btn9" />
<Button
android:id="#+id/btnCheck"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/btnCheckLabel"
android:layout_below="#+id/gridView1"
android:layout_alignTop="#+id/btn5"
android:layout_toRightOf="#+id/btn5"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:id="#+id/btnHint"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/btnHintLabel"
android:layout_alignTop="#+id/btn0"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignLeft="#+id/btnCheck"
android:layout_alignStart="#+id/btnCheck" />
<GridView
android:id="#+id/gridView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:numColumns="9"
android:columnWidth="0dp"
android:horizontalSpacing="5dp"
android:verticalSpacing="5dp"
android:clipChildren="true"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:background="#C0C0C0"
android:padding="5dp"
android:textSize="12sp"
android:stretchMode="columnWidth"
android:gravity="clip_vertical"
/>
</RelativeLayout>
MainActivity.java
package com.example.admin1.sudoku;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.DisplayMetrics;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.GridView;
import android.widget.ArrayAdapter;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.graphics.Color;
import android.widget.Toast;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import android.content.res.Resources;
import android.media.MediaPlayer;
public class MainActivity extends AppCompatActivity {
// Class that holds the creation of a Sudoku Puzzle
private SudokuPuzzle clsSudoku;
//Variables used throughout the program.
private final int iMaxCells = 81;
private String[] stResult; // Holds the solution to the current puzzle
private int[] iExcluded; // Holds all the blue cells (clues given to the user at the start)
// Placed into List for fast searching
private int iElement;
private boolean blShowResult; // Indicates if the user has clicked Show Result
private boolean blGiveHint; // Indicates if the user has clicked Give Hint
private boolean blSoundOn;
// UI Elements
private View tvCell;
private GridView gridView;
private Menu menu;
private MediaPlayer mp = null;
/* Lists
lstitems holds all the items in the current board including user entries
lstExclude holds all the blue cells (clues given to the user at the start)
adapter
*/
private List<String> lstItems;
private ArrayAdapter<String> adapter ;
private List<Integer> lstExcluded;
public MainActivity() {
stResult = new String[iMaxCells];
blGiveHint = false;
blShowResult = false;
iElement = 0;
blSoundOn = false;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Declare used buttons
Button btn1 = (Button) findViewById(R.id.btn1);
Button btn2 = (Button) findViewById(R.id.btn2);
Button btn3 = (Button) findViewById(R.id.btn3);
Button btn4 = (Button) findViewById(R.id.btn4);
Button btn5 = (Button) findViewById(R.id.btn5);
Button btn6 = (Button) findViewById(R.id.btn6);
Button btn7 = (Button) findViewById(R.id.btn7);
Button btn8 = (Button) findViewById(R.id.btn8);
Button btn9 = (Button) findViewById(R.id.btn9);
Button btn0 = (Button) findViewById(R.id.btn0);
Button btnHint = (Button) findViewById(R.id.btnHint);
Button btnCheck = (Button) findViewById(R.id.btnCheck);
//Creates a new Game
clsSudoku = new SudokuPuzzle();
newGame();
gridView = (GridView) findViewById(R.id.gridView1);
gridView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
if (blGiveHint == true){
blGiveHint = false;
//Initialise any hinted cells back to white
clearCells();
}
if (!blShowResult){
tvCell = gridView.getChildAt(iElement);
try{
tvCell.setBackgroundColor(Color.WHITE);
iElement = position;
tvCell = gridView.getChildAt(iElement);
tvCell.setBackgroundColor(Color.RED);
}
catch(Exception e){
}
}
}
});
gridView.setAdapter(adapter = new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_list_item_1, lstItems) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
view.setPadding(dpToPx(0, parent), 0, 0, 0);
view.setMinimumHeight(0);
if (position == iElement && !blShowResult){
view.setBackgroundColor(Color.RED);
}
else if (lstExcluded.contains(position)) {
view.setBackgroundColor(Color.WHITE);
}
else{
view.setBackgroundColor(Color.CYAN);
}
return view;
}
#Override
public boolean isEnabled(int position) {
// Item position which you want to disable.
if (!lstExcluded.contains(position) ) {
return false;
}
else {
return true;
}
}
});
btn1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if (adapter.isEnabled(iElement) && !blShowResult){
lstItems.set(iElement, "1");
adapter.notifyDataSetChanged();
}
}
});
btn2.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if (adapter.isEnabled(iElement) && !blShowResult){
lstItems.set(iElement, "2");
adapter.notifyDataSetChanged();
}
}
});
btn3.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if (adapter.isEnabled(iElement) && !blShowResult){
lstItems.set(iElement, "3");
adapter.notifyDataSetChanged();
}
}
});
btn4.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if (adapter.isEnabled(iElement) && !blShowResult){
lstItems.set(iElement, "4");
adapter.notifyDataSetChanged();
}
}
});
btn5.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if (adapter.isEnabled(iElement) && !blShowResult){
lstItems.set(iElement, "5");
adapter.notifyDataSetChanged();
}
}
});
btn6.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if (adapter.isEnabled(iElement) && !blShowResult){
lstItems.set(iElement, "6");
adapter.notifyDataSetChanged();
}
}
});
btn7.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if (adapter.isEnabled(iElement) && !blShowResult){
lstItems.set(iElement, "7");
adapter.notifyDataSetChanged();
}
}
});
btn8.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if (adapter.isEnabled(iElement) && !blShowResult){
lstItems.set(iElement, "8");
adapter.notifyDataSetChanged();
}
}
});
btn9.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if (adapter.isEnabled(iElement) && !blShowResult){
lstItems.set(iElement, "9");
adapter.notifyDataSetChanged();
}
}
});
btn0.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if (adapter.isEnabled(iElement) && !blShowResult){
lstItems.set(iElement, "");
adapter.notifyDataSetChanged();
}
}
});
btnHint.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
blGiveHint = true;
giveHint();
}
});
btnCheck.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
checkCorrect();
}
});
}
#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);
this.menu = 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
switch(id){
case R.id.new_game:
createNewGame();
return true;
case R.id.show_result:
getResult();
return true;
case R.id.sound_toggle:
setSoundSettings();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// Populate a list for fast searching later
private void populateExcludeList(int[] ipiArray){
lstExcluded.clear();
for (int iCnt = 0; iCnt < ipiArray.length; iCnt++){
lstExcluded.add(ipiArray[iCnt] - 1);
}
Collections.sort(lstExcluded);
}
// Populate a list for fast searching later
private void setBoard(String[] ipstArray){
lstItems.clear();
for (int iCnt = 0; iCnt < ipstArray.length; iCnt++){
lstItems.add(ipstArray[iCnt]);
}
}
// Create a new puzzle
private void newGame(){
String[] stNumbers = new String[iMaxCells];
blShowResult = false;
clsSudoku.swapTwoNumbers();
clsSudoku.swapTwoColumns();
clsSudoku.swapTwoBlocks();
clsSudoku.rotateNintyDegrees();
clsSudoku.clearNumbers();
stNumbers = clsSudoku.getResult("User");
stResult = clsSudoku.getResult("Result");
iExcluded = clsSudoku.getRemoved();
if (lstItems == null) {
lstItems = new ArrayList<String>(Arrays.asList(stNumbers));
}
else {
setBoard(stNumbers);
}
lstExcluded = new ArrayList<Integer>();
populateExcludeList(iExcluded);
iElement = lstExcluded.get(0);
}
private void createNewGame(){
if ( !lstItems.isEmpty() ){
lstItems.clear();
}
newGame();
adapter.notifyDataSetChanged();
}
private void getResult(){
blShowResult = true;
setBoard(stResult);
lstExcluded = new ArrayList<Integer>();
populateExcludeList(iExcluded);
adapter.notifyDataSetChanged();
}
public void giveHint(){
for (int iCnt = 0; iCnt < iMaxCells; iCnt++){
tvCell = gridView.getChildAt(iCnt);
try{
if (lstItems.get(iCnt).equalsIgnoreCase(stResult[iCnt]) == false && blGiveHint == true){
tvCell.setBackgroundColor(Color.RED);
}
else if(lstItems.get(iCnt).equalsIgnoreCase(stResult[iCnt]) && lstExcluded.contains(iCnt) ){
tvCell.setBackgroundColor(Color.WHITE);
}
}
catch(Exception e){
Toast.makeText(this, "Error: " + e.getMessage(),Toast.LENGTH_LONG).show();
}
}
}
public void checkCorrect(){
boolean blErrorFound = false;
int iCntErrors = 0;
int iCntBlanks = 0;
String stMessage = "";
for (int iCnt = 0; iCnt < iMaxCells; iCnt++){
if ( (lstItems.get(iCnt).equalsIgnoreCase("") == true)
){
iCntBlanks = iCntBlanks + 1;
blErrorFound = true;
}
else if((lstItems.get(iCnt).equalsIgnoreCase(stResult[iCnt]) == false) &&
(lstItems.get(iCnt).equalsIgnoreCase("") == false)
){
iCntErrors = iCntErrors + 1;
blErrorFound = true;
}
}
if (!blErrorFound){
stMessage = "Congratulations !!! Your solution is correct";
if (blSoundOn == true){
playSound("congratulations");
}
}
else{
stMessage = "You have " + iCntErrors + " errors and " + iCntBlanks + " squares left to do";
if (blSoundOn == true){
playSound("wrong");
}
}
Toast.makeText(getApplicationContext(), stMessage, Toast.LENGTH_LONG).show();
}
private void clearCells(){
for (int iCnt = 0; iCnt < iMaxCells; iCnt++){
tvCell = gridView.getChildAt(iCnt);
if(lstExcluded.contains(iCnt) ){
tvCell.setBackgroundColor(Color.WHITE);
}
}
}
private void setSoundSettings() {
MenuItem miMenu = menu.findItem(R.id.sound_toggle);
if (blSoundOn) {
blSoundOn = false;
miMenu.setTitle("Turn Sound On");
} else {
blSoundOn = true ;
miMenu.setTitle("Turn Sound Off");
}
}
public void playSound(String stFileName){
int iSoundId;
if (mp != null){
mp.reset();
mp.release();
}
Resources res = getApplicationContext().getResources();
iSoundId = res.getIdentifier(stFileName, "raw", getApplicationContext().getPackageName());
mp = MediaPlayer.create(getApplicationContext(), iSoundId);
mp.start();
}
public int dpToPx(int dp, View v) {
DisplayMetrics displayMetrics = v.getContext().getResources().getDisplayMetrics();
return Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
}
}
I am trying to convert my basic list view into a complex list view. I tried doing this by creating a product adapter. I keep getting an error on the super part saying "objects() in objects cannot be applied". I have not done this before, I was following a tutorial.
public class ProductAdapter {
ProductAdapter(Context context, String[] addProduct){
super(context,R.layout.list_item, addProduct);
}
#Override
public View getView(int position,View convertView, ViewGroup parent){
LayoutInflater momentsInflater = LayoutInflater.from(getContext());
View customView = momentsInflater.inflate(R.layout.list_item, parent, false);
ImageView imageView = (ImageView) customView.findViewById(R.id.imageView);
TextView momentsText = (TextView) customView.findViewById(R.id.textViewName);
ImageView momentsImage = (ImageView) customView.findViewById(R.id.imageView);
}
};
MainActivity
public class MainActivity extends Activity {
private ListView listView;
private String[] details;
public static ArrayList<Product> product = new ArrayList<>();
boolean firstRun = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
}
#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 presses on the action bar items
switch (item.getItemId()) {
case R.id.action_AddProduct:
startActivity(new Intent(MainActivity.this, Activity_addProduct.class));
case R.id.action_Information:
startActivity(new Intent(MainActivity.this, Activity_addProduct.class));
return true;
case R.id.action_Home:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onResume() {
super.onResume();
DatabaseHandler db = new DatabaseHandler(this);
String[] productStrings;
if (firstRun) {
String[] placeHolterStrings = {"", ""};
productStrings = placeHolterStrings;
firstRun = false;
} else {
product = db.getAllContacts();
productStrings = new String [product.size()];
for (int i = 0; i < product.size(); i++) {
productStrings[i] = product.get(i).toString();
}
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, productStrings);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
}
);
}
}
Myproduct class
public class Product {
private int id;
private String productName;
private String productModel;
public Product(int id, String productName, String productModel) {
this.id = id;
this.productName = productName;
this.productModel = productModel;
}
public Product() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getProductName() {
return productName;
}
public void setName(String productName) {
this.productName = productName;
}
public String getProductModel() {
return productModel;
}
public void setProductModel(String productModel) {
this.productModel = productModel;
}
#Override
public String toString() {
return this.productName + " " + this.productModel;
}
}
List_item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:id="#+id/imageView"
android:layout_width="85dp"
android:layout_height="85dp"
android:background="#android:color/darker_gray"
android:padding="8dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:scaleType="centerCrop" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginTop="20dp"
android:orientation="vertical">
<TextView
android:id="#+id/textViewName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="first + last name"
android:textSize="16dp" />
<TextView
android:id="#+id/textViewDetail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text="details of the candidate"
android:textSize="12dp" />
</LinearLayout>
</LinearLayout>
A complex list view is the example below:
I'm working with fragments (API 4.1) and I want to let the user press a button, access his/her gallery, select an image, and have that image display an imageview on the original fragment where the button appeared. I'm using the following code:
public class FillBox1Frag extends Fragment {
Button addPics, placeBox;
ImageView imgView;
Bitmap b;
Uri photoUri;
LinearLayout fillBoxLayout;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
if (container == null) {
return null;
}
fillBoxLayout = (LinearLayout) inflater.inflate(R.layout.fillbox1_frag,
container, false);
newBin = new Bin();
addPics = (Button) fillBoxLayout.findViewById(R.id.bPics);
imgView = (ImageView) fillBoxLayout.findViewById(R.id.imageView1);
addPics.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent picChooser = new Intent(Intent.ACTION_GET_CONTENT,
MediaStore.Images.Media.INTERNAL_CONTENT_URI);
picChooser.setType("image/*");
startActivityForResult(picChooser, 12345);
}
});
return fillBoxLayout;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 12345:
if (resultCode == 12345) {
photoUri = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = FillBox1Frag.this.getActivity()
.getContentResolver()
.query(photoUri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
b = BitmapFactory.decodeFile(filePath);
imgView.setImageBitmap(b);
}
}
}
I access the Gallery, but upon selection, it just returns to the original fragment and doesn't display the image. Here's my XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fillbox"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:tag="fillbox" >
<Button
android:id="#+id/bPics"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="89dp"
android:background="#drawable/buttonpics" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
I've found plenty of answers dealing with a similar question, but nothing that has been able to help me with how to create this process using fragments. Any ideas on how to get my selected image to appear in the ImageView? Thanks for the help!
I am working with two fragments in Android Honeycomb (Tab). In the left is a ListView and in the right is a preview of the item selected from the list. When one of the buttons is clicked, I want to show different layouts on the left. How is it possible?
Thanks in advance.
You can do this, I made the same thing with use of these links, here is my code which I am sharing with you in the hope that it will be helpful for you... You will first have to create 4 layouts. 2 of which will be for landscape mode, one for portrait mode and another for tablets. You have to create a couple more folders for layouts and their name should be like layout-xlarge and layout-xlarge-port, this way you can create fragments for both mobile devices and tablets.
MasterFragment Activity:
public class MasterFragment extends ListFragment {
Boolean isDualPane;
int position;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayList<String> parkNames = new ArrayList<String>();
for (Park park : Resort.PARKS) {
parkNames.add(park.getName());
}
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, parkNames));
View detailFrame = getActivity().findViewById(R.id.detail);
isDualPane = detailFrame != null && detailFrame.getVisibility() == View.VISIBLE;
if (savedInstanceState != null) {
position = savedInstanceState.getInt("position", 0);
}
if (isDualPane) {
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
showDetail(position);
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("position", position);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
showDetail(position);
}
void showDetail(int position) {
this.position = position;
if (isDualPane) {
getListView().setItemChecked(position, true);
DetailFragment detailFragment = (DetailFragment) getFragmentManager()
.findFragmentById(R.id.detail);
if (detailFragment == null || detailFragment.getIndex() != position) {
detailFragment = new DetailFragment(position);
FragmentTransaction ft = getFragmentManager()
.beginTransaction();
ft.replace(R.id.detail, detailFragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
} else {
Intent intent = new Intent();
intent.setClass(getActivity(), DetailActivity.class);
intent.putExtra("position", position);
startActivity(intent);
}
}
}
Second Activity - DetailFragment Activity:
public class DetailActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detail_act);
Bundle bundle = getIntent().getExtras();
int position = bundle.getInt("position");
System.out.println("RR : position is : " + position);
Integer[] images = { R.drawable.pic1, R.drawable.pic2, R.drawable.pic3,
R.drawable.pic4, R.drawable.pic5, R.drawable.pic6,
R.drawable.pic7, R.drawable.pic8, R.drawable.pic9,
R.drawable.pic10, R.drawable.pic11, R.drawable.pic12,
R.drawable.pic13 };
final ImageView imgview = (ImageView) findViewById(R.id.imageView1);
imgview.setImageResource(images[position]);
// DetailFragment detailFragment = new DetailFragment(position);
// FragmentManager fm = getSupportFragmentManager();
// FragmentTransaction ft =fm.beginTransaction();
// ft.add(android.R.id.content, detailFragment).commit();
}
}
Now you have to create a third activity, MasterGridActivity for my images which I am using for showing in fragment in GridView.
public class MasterGridActivity extends Fragment {
Boolean isDualPane;
GridView gridView;
ListView listView;
int position;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.gridview, container, false);
gridView = (GridView) view.findViewById(R.id.gridViewImage);
gridView.setAdapter(new MyAdapter(view.getContext()));
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
View detailFrame = getActivity().findViewById(R.id.detail);
isDualPane = detailFrame != null && detailFrame.getVisibility() == View.VISIBLE;
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
if (!isDualPane) {
Intent intent = new Intent();
intent.setClass(getActivity(), DetailActivity.class);
intent.putExtra("position", pos);
startActivity(intent);
} else {
DetailFragment detailFragment = (DetailFragment) getFragmentManager().findFragmentById(R.id.detail);
if (detailFragment == null || detailFragment.getIndex() != pos) {
detailFragment = new DetailFragment(pos);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.detail, detailFragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
}
}
});
super.onActivityCreated(savedInstanceState);
}
}
Now here is my image adapter - MyAdapter - for my images which extends a BaseAdapter.
public class MyAdapter extends BaseAdapter {
private Context mContext;
public MyAdapter(Context c) {
mContext = c;
}
#Override
public int getCount() {
return mThumbIds.length;
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(100, 100));
imageView.setImageResource(mThumbIds[position]);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(0, 0, 0, 0);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
static Integer[] mThumbIds = { R.drawable.pic1, R.drawable.pic2,
R.drawable.pic3, R.drawable.pic4, R.drawable.pic5, R.drawable.pic6,
R.drawable.pic7, R.drawable.pic8, R.drawable.pic9,
R.drawable.pic10, R.drawable.pic11, R.drawable.pic12,
R.drawable.pic13,
};
}
Now I am sharing the XML files for these fragments.
Main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<fragment
android:id="#+id/master"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="org.fragment.MasterGridActivity" />
</LinearLayout>
gridview.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gridViewImage"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:numColumns="auto_fit"
android:columnWidth="90dp"
android:horizontalSpacing="10dp"
android:verticalSpacing="10dp"
android:gravity="center"
android:stretchMode="columnWidth" />
</LinearLayout>
detail_fragment.xml: This XML is for showing the detail in another fragment.
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="8dp" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:padding="8dp" />
</LinearLayout>
</ScrollView>
detail_act.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="#drawable/ic_launcher" />
</LinearLayout>
Make the same XML for landscape mode and for tablets. It's working fine for me. Hope it will helpful for you.
You need to define an event callback to the activity activity callback. That is, your left fragment must first notify the container activity that an event occurred (i.e. one of the list items were selected). The container activity will then pass this information to the right fragment, which will then update its UI accordingly.
I could explain this in more detail, but there are several tutorials on the internet that teach just that. I suggest you read through some of them, as the concept will make a lot more sense once you do.