I have app in which I have ImageView. I open new activity, where I paint something by finger and this bitmap return to my ImageView. everything is ok but when I change orientation now, my activity with ImageView is repaint or restart and imageview is empty. I try everything, I try SaveState and restore state, try configurationChange, and other, but nothing is working...
package jilova.Android.TextFolder;
import java.io.ByteArrayOutputStream;
import jilova.Android.Enums;
import jilova.Android.R;
import jilova.Android.DatabaseFolder.LocalDB;
import jilova.Android.DatabaseFolder.RequestRow;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.Toast;
public class Text extends Activity{
private static EditText t1;
private static EditText t2;
private static EditText t3;
private static EditText t4;
private static ImageView iv1;
private static Context c;
private static Activity ac;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.text);
Object o = this.getLastNonConfigurationInstance();
if(o!=null)
{
Enums.sign=(Bitmap)o;
}
c=this.getApplicationContext();
ac=this;
ImageView iv = (ImageView)this.findViewById(R.id.imageView1);
iv.setDrawingCacheEnabled(true);
t1 = (EditText)this.findViewById(R.id.TEXTNote);
t2 = (EditText)this.findViewById(R.id.TextET2);
t3 = (EditText)this.findViewById(R.id.TextET3);
t4 = (EditText)this.findViewById(R.id.TextET4);
//iv.setImageBitmap(Bitmap.createScaledBitmap(Enums.sign, iv.getWidth(), iv.getHeight(), false).copy(Config.ARGB_8888, true));
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
}
// Checks whether a hardware keyboard is available
if (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO) {
} else if (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_YES) {
}
}
public static RequestRow getData()
{
RequestRow row = new RequestRow();
row.SetREQUESTNOTE(t1.getText().toString());
row.SetREQUESTTYPEID(Integer.parseInt(t2.getTag().toString()));
row.SetTYPTECHUDRZBYID(Integer.parseInt(t3.getTag().toString()));
row.SetOBJECTID(Integer.parseInt(t4.getTag().toString()));
return row;
}
public static void setData(String REQUESTTYPEID ,String TYPTECHUDRZBYID,String OBJECTID,String REQUESTNOTE,String REQUESTID)
{
t1.setText(REQUESTNOTE);
t2.setTag(REQUESTTYPEID);
t2.setText(LocalDB.dbGetRequestTypeByID(c, Integer.parseInt(REQUESTTYPEID)));
t3.setTag(TYPTECHUDRZBYID);
t3.setText(LocalDB.dbGetTypTechUdrzbyByID(c, Integer.parseInt(TYPTECHUDRZBYID)));
t4.setTag(OBJECTID);
t4.setText(LocalDB.dbGetObjectByID(c, Integer.parseInt(OBJECTID)));
Bitmap b = LocalDB.dbGetDocumentByID(c, Integer.parseInt(REQUESTID));
if(b!=null)
{
iv1.setImageBitmap(b);
}
}
public static Bitmap getSign()
{
iv1.buildDrawingCache();
Bitmap ret = iv1.getDrawingCache();
if(Enums.EmptySignHash)
{
return null;
}
else
{
return ret;
}
}
public void Sign(View button)
{
Intent s = new Intent(Text.this,Sign.class);
startActivityForResult(s,Enums.SIGNREQUESTID);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(resultCode!=Activity.RESULT_OK)
{
return;
}
Enums.IDLocal=-1;
if(requestCode==Enums.GetData)
{
Bundle extras = data.getExtras();
if(extras !=null)
{
EditText et = (EditText)this.findViewById(extras.getInt("ViewID"));
et.setText(extras.getString("Value"));
et.setTag(extras.get("ID"));
}
}
else if(requestCode==Enums.SIGNREQUESTID)
{
Bundle extras = data.getExtras();
if(extras !=null)
{
ImageView iv = (ImageView)this.findViewById(R.id.imageView1);
try
{
byte[] b = extras.getByteArray("Bitmap");
Enums.sign = Bitmap.createBitmap(BitmapFactory.decodeByteArray(b, 0, b.length), 0, 0, ac.getWindowManager().getDefaultDisplay().getWidth(), 200);
iv.setImageBitmap(Bitmap.createScaledBitmap(Enums.sign, iv.getWidth(), iv.getHeight(), false));
}
catch(Exception e)
{
int a=0;
}
}
Enums.EmptySignHash=false;
}
}
public static void DeleteAll()
{
EditText t = (EditText)ac.findViewById(R.id.TEXTNote);
t.setText("");
t.setTag(-1);
t = (EditText)ac.findViewById(R.id.TextET2);
t.setText("");
t.setTag(-1);
t = (EditText)ac.findViewById(R.id.TextET3);
t.setText("");
t.setTag(-1);
t = (EditText)ac.findViewById(R.id.TextET4);
t.setText("");
t.setTag(-1);
ImageView iv = (ImageView)ac.findViewById(R.id.imageView1);
//Bitmap b = Bitmap.createBitmap(Enums.createColors(), 0, Enums.STRIDE, Enums.WIDTH, Enums.HEIGHT, Bitmap.Config.ARGB_8888).copy(Bitmap.Config.ARGB_8888, true);
iv.setImageBitmap(Bitmap.createScaledBitmap(Enums.sign, ac.getWindowManager().getDefaultDisplay().getWidth(), iv.getLayoutParams().height, false));
Enums.EmptySignHash=true;
}
public void Delete(View button)
{
EditText t = (EditText)this.findViewById(R.id.TEXTNote);
t.setText("");
t.setTag(-1);
t = (EditText)this.findViewById(R.id.TextET2);
t.setText("");
t.setTag(-1);
t = (EditText)this.findViewById(R.id.TextET3);
t.setText("");
t.setTag(-1);
t = (EditText)this.findViewById(R.id.TextET4);
t.setText("");
t.setTag(-1);
ImageView iv = (ImageView)this.findViewById(R.id.imageView1);
//Bitmap b = Bitmap.createBitmap(Enums.createColors(), 0, Enums.STRIDE, Enums.WIDTH, Enums.HEIGHT, Bitmap.Config.ARGB_8888).copy(Bitmap.Config.ARGB_8888, true);
iv.setImageBitmap(Bitmap.createScaledBitmap(Enums.sign, ac.getWindowManager().getDefaultDisplay().getWidth(), iv.getLayoutParams().height, false));
Enums.EmptySignHash=true;
}
public void GetData(View button)
{
if(button.getId()==R.id.TextIB3)
{
Intent ChooseAction = new Intent(Text.this,ChooseData.class);
Enums.Data = LocalDB.dbLocalSelect(this.getApplicationContext(),"Select typtechudrzbyid,typtechudrzbydesc from typtechudrzby");
if(Enums.Data==null)
{
Toast t=Toast.makeText(this, "Chyba lokalni db", Toast.LENGTH_SHORT);
t.setGravity(Gravity.CENTER, 0, 0);
t.show();
return;
}
ChooseAction.putExtra("ViewID", R.id.TextET3);
startActivityForResult(ChooseAction,Enums.GetData);
}
else if(button.getId()==R.id.TextIB2)
{
Intent ChooseAction = new Intent(Text.this,ChooseData.class);
Enums.Data = LocalDB.dbLocalSelect(this.getApplicationContext(),"Select Requesttypeid,requestname from requesttype");
if(Enums.Data==null)
{
Toast t=Toast.makeText(this, "Chyba lokalni db", Toast.LENGTH_SHORT);
t.setGravity(Gravity.CENTER, 0, 0);
t.show();
return;
}
ChooseAction.putExtra("ViewID", R.id.TextET2);
startActivityForResult(ChooseAction,Enums.GetData);
}
else if(button.getId()==R.id.TextIB4)
{
Intent ChooseAction = new Intent(Text.this,TreeData.class);
Enums.TreeData = LocalDB.dbLocalSelectTree(this.getApplicationContext(),"Select objectid,objectname,objectref from Objects");
if(Enums.TreeData==null)
{
Toast t=Toast.makeText(this, "Chyba lokalni db", Toast.LENGTH_SHORT);
t.setGravity(Gravity.CENTER, 0, 0);
t.show();
return;
}
ChooseAction.putExtra("ViewID", R.id.TextET4);
startActivityForResult(ChooseAction,Enums.GetData);
}
else
{
//throw new Exception();
}
}
}
When a configuration change such as a screen rotation occurs by default your Activity is destroyed and then recreated (onDestroy of the current activity is called, and then the onCreate of a new version of your activity is called).
You can either:
Stop Android recreating your activity when a configuration change occurs. To do this add android:configChanges="keyboardHidden|orientation" to the activity tag in your manifest. This is not recommend since if you want a different layout etc for different configurations you will have to handle changing the layout yourself.
Override onRetainNonConfigurationInstance and return your bitmap from that. In onCreate check if the last non-configuration instance is not null, in which case cast it to a bitmap and then set the image.
For the latter case, use something like the following:
#Override
public void onCreate(Bundle savedInstanceState) {
...
// Check if our activity was just destroyed and re-created
final Object retainedFromConfigChange = getLastNonConfigurationInstance();
if (retainedFromConfigChange != null) {
// Activity has just been recreated, get the image we were working on
// before the configuration change
ImageView iv = (ImageView)ac.findViewById(R.id.imageView1);
iv.setImageBitmap((Bitmap) retainedFromConfigChange);
}
...
}
#Override
public Object getLastNonConfigurationInstance() {
ImageView iv = (ImageView)ac.findViewById(R.id.imageView1);
// We have to return a plain old Bitmap and not a drawable of any sorts
// or we will get memory leaks so we need to extract the bitmap from the drawable
return ((BitmapDrawable) iv.getDrawable()).getBitmap();
}
I think you forgot to override the onRetainNonConfigurationInstance() method where you return your bitmap so it will be passed to the new activity. In the new activity you can retrieve the bitmap as you already do by calling getLastNonConfigurationInstance().
When the configuration is changed, the whole view is re-created. So, we need to retain the imageView resource. The best way to do this is to handle the orientation change by creating a Retained fragment.
You can find the perfect documentation on Android developer's page.
P.S.: Adding android:configChanges="keyboardHidden|orientation" to the manifest is highly not recommended.
Related
I want put edittext from first activity to new secondactivity view text.
What to do when I have an erro like this displayed in android monitor :
com.example.xx.DrawerAddAd.seeAdd(DrawerAddAd.java:129)
com.example.xx.DrawerAddAd.access$100(DrawerAddAd.java:40)
com.example.xx.DrawerAddAd$2.onClick(DrawerAddAd.java:116)
also:
Render problem:
Couldn't resolve resource #id/visible
Tip: Try to refresh the layout.
DrawerAddAd class code:
package com.example.xx.drawer;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Camera;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Spinner;
import com.example.xx.R;
import com.example.xxx.model.POJO.view.ProductDetails;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import butterknife.BindView;
public class DrawerAddAd extends AppCompatActivity {
public static ArrayList<String> fragments = new ArrayList<>();
private final int REQUEST_CODE = 1;
private ImageButton camera_imageButton;
private Spinner spinner_category;
private Button button_seeAd_product;
private Button button_add_product;
#BindView(R.id.title_Ad_editText)
EditText titleAd_editText;
#BindView(R.id.text_Ad_editText)
EditText textAd_editText;
#BindView(R.id.price_editText)
EditText price_editText;
#BindView(R.id.checkBox_season)
CheckBox checkBox_season;
#BindView(R.id.checkBox_year)
CheckBox checkBox_year;
#BindView(R.id.checkBox_detail)
CheckBox checkBox_detail;
#BindView(R.id.checkBox_wholesale)
CheckBox checkBox_whoLesale;
private int REQUEST_CAMERA = 1, SELECT_FILE = 1;
private Button btnSelect;
private ImageView Image;
private String userChosenTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drawer_add_ad);
final TextInputLayout title_ad_layout = (TextInputLayout) findViewById(R.id.add_title_ad_layout);
final TextInputLayout text_ad_layout = (TextInputLayout) findViewById(R.id.add_text_ad_layout);
final TextInputEditText title_Ad_editText = (TextInputEditText) findViewById(R.id.title_Ad_editText);
final TextInputEditText text_Ad_editText = (TextInputEditText) findViewById(R.id.text_Ad_editText);
setTextWatcher(title_Ad_editText, title_ad_layout);
setTextWatcher(text_Ad_editText, text_ad_layout);
spinner_category = (Spinner) findViewById(R.id.spinner_category);
button_seeAd_product = (Button) findViewById(R.id.button_seeAd_product);
button_add_product = (Button) findViewById(R.id.button_ad_product);
camera_imageButton = (ImageButton) findViewById(R.id.camera_imageButton);
camera_imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
button_seeAd_product.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean error = false;
if (TextUtils.isEmpty(title_Ad_editText.getText().toString())) {
title_ad_layout.setError(getString(R.string.empty_field));
error = true;
}
if (TextUtils.isEmpty(text_Ad_editText.getText().toString())) {
text_ad_layout.setError(getString(R.string.empty_field));
error = true;
}
if (!error) {
seeAdd();
}
}
});
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.fragments, R.layout.support_simple_spinner_dropdown_item);
adapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
spinner_category.setAdapter(adapter);
}
private void seeAdd() {
Intent intent = new Intent(getApplicationContext(), ProductDetails.class);
intent.putExtra("title",titleAd_editText.getText().toString());
intent.putExtra("text", textAd_editText.getText().toString());
// ImageView imageView =
// String title = titleAd_editText.getText().toString();
// String text = textAd_editText.getText().toString();
// String price = price_editText.getText().toString();
//
//
// intent.putExtra("titleAdd", title);
// intent.putExtra("textAdd", text);
// intent.putExtra("price", price);
startActivity(intent);
}
private void onCheckboxClicked(View view) {
boolean checked = ((CheckBox) view).isChecked();
switch (view.getId()) {
case R.id.checkBox_season:
if (checked) {
} else {
}
break;
case R.id.checkBox_year:
if (checked) {
} else {
}
break;
case R.id.checkBox_detail:
if (checked) {
} else {
}
break;
case R.id.checkBox_wholesale:
if (checked) {
} else {
}
break;
}
}
private void setTextWatcher(final TextInputEditText editText, final TextInputLayout inputLayout) {
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (inputLayout.isErrorEnabled()) {
inputLayout.setErrorEnabled(false);
}
}
#Override
public void afterTextChanged(Editable editable) {
}
});
}
private void selectImage() {
final CharSequence[] items = {"Zrób zdjęcie", "Wybierz z katalogu", "Anuluj"};
AlertDialog.Builder builder = new AlertDialog.Builder(DrawerAddAd.this);
builder.setTitle("Dodaj zdjęcie");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result = Utility.checkPermission(DrawerAddAd.this);
if (items[item].equals("Zrób zdjęcie")) {
userChosenTask = "Zrób zdjęcie";
if (result)
cameraIntent();
} else if (items[item].equals("Wybierz z katalogu")) {
userChosenTask = "Wybierz z katalogu";
if (result)
galleryIntent();
} else if (items[item].equals("Anuluj")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}
private void cameraIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
private void galleryIntent() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Wybierz plik"), SELECT_FILE);
}
private void onSelectFromGalleryResult(Intent data) {
Bitmap bm = null;
if (data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
Image.setImageBitmap(bm);
}
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Image.setImageBitmap(thumbnail);
}
}
ProductDetails class code:
package com.example.xxx.model.POJO.view;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.TextView;
import com.example.xxx.R;
public class ProductDetails extends AppCompatActivity {
private TextView title, text, price, date;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_details);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
title = (TextView) findViewById(R.id.title_textView);
text = (TextView) findViewById(R.id.text_textView);
Intent intent = getIntent();
// Bundle bundle = getIntent().getExtras();
String title_textView = intent.getStringExtra("titleAdd");
String text_textView = intent.getStringExtra("textAdd");
title.setText(title_textView);
text.setText(text_textView);
// price = (TextView) findViewById(R.id.price_textView);
// date = (TextView) findViewById(R.id.date_textView);
// String titleAdd = bundle.getString("titleAdd");
// String textAdd = bundle.getString("textAdd");
// String price = bundle.getString("price");
// title.setText(titleAdd);
// text.setText(textAdd);
// price.setText(price);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
}
I don't know what to do ...
Thanks, Slawek.
it means title_Ad_editText is null.
Check your xml file and title_Ad_editText variable.
couple things I could see, redo this:
private void seeAdd() {
Intent intent = new Intent(getApplicationContext(), ProductDetails.class);
intent.putExtra("title",titleAd_editText.getText().toString());
intent.putExtra("text", textAd_editText.getText().toString());
to this:
private void seeAdd() {
Intent intent = new Intent(DrawerAddAd.this, ProductDetails.class);
intent.putExtra("title",titleAd_editText.getText().toString());
intent.putExtra("text", textAd_editText.getText().toString());
then in your intent, you need to call the extra exactly as set, change this:
Intent intent = getIntent();
// Bundle bundle = getIntent().getExtras();
String title_textView = intent.getStringExtra("titleAdd");
String text_textView = intent.getStringExtra("textAdd");
to this:
Intent intent = getIntent();
// Bundle bundle = getIntent().getExtras();
String title_textView = intent.getStringExtra("title");
String text_textView = intent.getStringExtra("text");
What I want the app to do after scanning is to dial the number instead of displaying it.So I'm new to Android developing and zxing library. I've been able to create a standalone QR scanner app using the zxing library but the issue is that when it scans the QR code, I want it to either open the URL in a browser or do something else based on the content of the QR instead of displaying the string content of the QR code. Example, if the string content of the QR code is a URL "www.stackoverflow.com", I want the app to take me to the site instead of displaying the string content of the QR code.
This is the code for my CaptureActivity
package com.skyers.jwetherell.quick_response_code;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.skyers.google.zxing.Result;
import com.skyers.google.zxing.ResultMetadataType;
import com.skyers.jwetherell.quick_response_code.result.ResultHandler;
import com.skyers.jwetherell.quick_response_code.result.ResultHandlerFactory;
import java.text.DateFormat;
import java.util.Date;
import java.util.EnumSet;
import java.util.Map;
import java.util.Set;
public class CaptureActivity extends com.skyers.jwetherell.quick_response_code.DecoderActivity {
private static final String TAG = CaptureActivity.class.getSimpleName();
private static final Set<ResultMetadataType> DISPLAYABLE_METADATA_TYPES = EnumSet.of(ResultMetadataType.ISSUE_NUMBER, ResultMetadataType.SUGGESTED_PRICE,
ResultMetadataType.ERROR_CORRECTION_LEVEL, ResultMetadataType.POSSIBLE_COUNTRY);
private TextView statusView = null;
private View resultView = null;
private boolean inScanMode = false;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.capture);
Log.v(TAG, "onCreate()");
resultView = findViewById(R.id.result_view);
statusView = (TextView) findViewById(R.id.status_view);
inScanMode = false;
}
#Override
protected void onDestroy() {
super.onDestroy();
Log.v(TAG, "onDestroy()");
}
#Override
protected void onResume() {
super.onResume();
Log.v(TAG, "onResume()");
}
#Override
protected void onPause() {
super.onPause();
Log.v(TAG, "onPause()");
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (inScanMode)
finish();
else
onResume();
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
public void handleDecode(Result rawResult, Bitmap barcode) {
drawResultPoints(barcode, rawResult);
ResultHandler resultHandler = ResultHandlerFactory.makeResultHandler(this, rawResult);
handleDecodeInternally(rawResult, resultHandler, barcode);
}
protected void showScanner() {
inScanMode = true;
resultView.setVisibility(View.GONE);
statusView.setText(R.string.msg_default_status);
statusView.setVisibility(View.VISIBLE);
viewfinderView.setVisibility(View.VISIBLE);
}
protected void showResults() {
inScanMode = false;
statusView.setVisibility(View.GONE);
viewfinderView.setVisibility(View.GONE);
resultView.setVisibility(View.VISIBLE);
}
// Put up our own UI for how to handle the decodBarcodeFormated contents.
private void handleDecodeInternally(Result rawResult, ResultHandler resultHandler, Bitmap barcode) {
onPause();
showResults();
ImageView barcodeImageView = (ImageView) findViewById(R.id.barcode_image_view);
if (barcode == null) {
barcodeImageView.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.skyers));
} else {
barcodeImageView.setImageBitmap(barcode);
}
TextView formatTextView = (TextView) findViewById(R.id.format_text_view);
formatTextView.setText(rawResult.getBarcodeFormat().toString());
TextView typeTextView = (TextView) findViewById(R.id.type_text_view);
typeTextView.setText(resultHandler.getType().toString());
DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
String formattedTime = formatter.format(new Date(rawResult.getTimestamp()));
TextView timeTextView = (TextView) findViewById(R.id.time_text_view);
timeTextView.setText(formattedTime);
TextView metaTextView = (TextView) findViewById(R.id.meta_text_view);
View metaTextViewLabel = findViewById(R.id.meta_text_view_label);
metaTextView.setVisibility(View.GONE);
metaTextViewLabel.setVisibility(View.GONE);
Map<ResultMetadataType, Object> metadata = rawResult.getResultMetadata();
if (metadata != null) {
StringBuilder metadataText = new StringBuilder(20);
for (Map.Entry<ResultMetadataType, Object> entry : metadata.entrySet()) {
if (DISPLAYABLE_METADATA_TYPES.contains(entry.getKey())) {
metadataText.append(entry.getValue()).append('\n');
}
}
if (metadataText.length() > 0) {
metadataText.setLength(metadataText.length() - 1);
metaTextView.setText(metadataText);
metaTextView.setVisibility(View.VISIBLE);
metaTextViewLabel.setVisibility(View.VISIBLE);
}
}
TextView contentsTextView = (TextView) findViewById(R.id.contents_text_view);
CharSequence displayContents = resultHandler.getDisplayContents();
contentsTextView.setText(displayContents);
// Crudely scale betweeen 22 and 32 -- bigger font for shorter text
int scaledSize = Math.max(22, 32 - displayContents.length() / 4);
contentsTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, scaledSize);
}
}
And this is the code for my ResultHandler
package com.skyers.jwetherell.quick_response_code.result;
import android.app.Activity;
import com.skyers.google.zxing.Result;
import com.skyers.google.zxing.client.result.ParsedResult;
import com.skyers.google.zxing.client.result.ParsedResultType;
public abstract class ResultHandler {
private final ParsedResult result;
private final Activity activity;
private final Result rawResult;
ResultHandler(Activity activity, ParsedResult result) {
this(activity, result, null);
}
ResultHandler(Activity activity, ParsedResult result, Result rawResult) {
this.result = result;
this.activity = activity;
this.rawResult = rawResult;
}
public ParsedResult getResult() {
return result;
}
Activity getActivity() {
return activity;
}
public Result getRawResult() {
return rawResult;
}
public boolean areContentsSecure() {
return false;
}
public CharSequence getDisplayContents() {
String contents = result.getDisplayResult();
return contents.replace("\r", "");
}
public abstract int getDisplayTitle();
public final ParsedResultType getType() {
return result.getType();
}
}
You question is not very clear, you have to put some source code to explain your issue.
You could use this library: https://github.com/zxing/zxing/wiki/Scanning-Via-Intent
and in your activity:
private void launchScanBarcode(){
IntentIntegrator integrator = new IntentIntegrator(yourActivity);
integrator.initiateScan();
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanResult != null) {
// handle scan result with scanResult.getContents() or scanResult.getRawBytes()
}
// else continue with any other code you need in the method
...
}
Would anyone tell me how to pass images from one activity to another activity using extras (the idea is). I am displaying a set of images in activity1 as a horizontal scroll view. When I click on an image it should be displayed in another activity (activity2) with totally different layout.
I'll be satisfied if the explanation is done with json as well I have tried this (http://www.vogella.com/tutorials/AndroidIntent/article.html) tutorial but can't really find the answer.
MAIN ACTIVITY:
package com.example.user.horizontal;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
public class MainActivity extends Activity implements OnClickListener {
ImageView Display;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView im1 = (ImageView) findViewById(R.id.image1);
ImageView im2 = (ImageView) findViewById(R.id.image2);
ImageView im3 = (ImageView) findViewById(R.id.image3);
ImageView im4 = (ImageView) findViewById(R.id.image4);
ImageView im5 = (ImageView) findViewById(R.id.image5);
ImageView im6 = (ImageView) findViewById(R.id.image6);
ImageView im7 = (ImageView) findViewById(R.id.image7);
im1.setOnClickListener(this);
im2.setOnClickListener(this);
im3.setOnClickListener(this);
im4.setOnClickListener(this);
im5.setOnClickListener(this);
im6.setOnClickListener(this);
im7.setOnClickListener(this);
}
public void onClick(View v) {
Intent clickimage = new Intent(this, OnClick.class);
switch (v.getId()) {
case R.id.image1:
Display.setImageResource(R.drawable.images1);
clickimage.putExtra("display1", "images1");
startActivity(clickimage);
break;
case R.id.image2:
Display.setImageResource(R.drawable.images2);
clickimage.putExtra("display2", "pic2filename");
startActivity(clickimage);
break;
case R.id.image3:
Display.setImageResource(R.drawable.images8);
clickimage.putExtra("display3", "pic3filename");
startActivity(clickimage);
break;
case R.id.image4:
Display.setImageResource(R.drawable.images4);
clickimage.putExtra("display4", "pic4filename");
startActivity(clickimage);
break;
case R.id.image5:
Display.setImageResource(R.drawable.images5);
clickimage.putExtra("display5", "pic5filename");
startActivity(clickimage);
break;
case R.id.image6:
Display.setImageResource(R.drawable.images6);
clickimage.putExtra("display6", "pic6filename");
startActivity(clickimage);
break;
case R.id.image7:
Display.setImageResource(R.drawable.images8);
clickimage.putExtra("display7", "pic7filename");
startActivity(clickimage);
break;
}
}
SECOND ACTIVITY :
package com.example.user.horizontal;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;
public class OnClick extends Activity{
private Bitmap mImage1;
private Bitmap mImage2;
private Bitmap mImage3;
private Bitmap mImage4;
private Bitmap mImage5;
private Bitmap mImage6;
private Bitmap mImage7;
private Bitmap mImage8;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.onclick);
Bundle bundle = getIntent().getExtras();
String imageName = bundle.getString("display");
// click listeners
ImageView imageView = (ImageView)findViewById(R.id.image1);
mImage1 = BitmapFactory.decodeResource(getResources(), R.drawable.images1);
mImage2 = BitmapFactory.decodeResource(getResources(), R.drawable.images2);
mImage3 = BitmapFactory.decodeResource(getResources(), R.drawable.images4);
mImage4 = BitmapFactory.decodeResource(getResources(), R.drawable.images5);
mImage5 = BitmapFactory.decodeResource(getResources(), R.drawable.images6);
mImage6 = BitmapFactory.decodeResource(getResources(), R.drawable.images7);
mImage7 = BitmapFactory.decodeResource(getResources(), R.drawable.images8);
mImage8 = BitmapFactory.decodeResource(getResources(), R.drawable.images);
if(imageName.matches("images1")) {
String b = bundle.getString("b");
imageView.setImageBitmap(mImage1);
}
else if (imageName.matches("pic2filename")) {
imageView.setImageBitmap(mImage2);
}
else if (imageName.matches("pic3filename")) {
imageView.setImageBitmap(mImage3);
}
else if (imageName.matches("pic4filename")) {
imageView.setImageBitmap(mImage4);
}
else if (imageName.matches("pic2filename")) {
imageView.setImageBitmap(mImage5);
}
else if (imageName.matches("pic5filename")) {
imageView.setImageBitmap(mImage6);
}
else if (imageName.matches("pic6filename")) {
imageView.setImageBitmap(mImage7);
}
else if (imageName.matches("pic7filename")) {
imageView.setImageBitmap(mImage8);
}
}
}
I am new to Java and Android.
Try passing the image file path or image url to next activity using extras in android
Pass Bitmap using intent :
Intent intent = new Intent(this, NewActivity.class);
intent.putExtra("BitmapImage", bitmap);
and retrieve it on the other end:
Intent intent = getIntent();
Bitmap bitmap = (Bitmap) intent.getParcelableExtra("BitmapImage");
Don't pass images between activities.
You should pass the path to image in Intent and show it in your new Activity. This is a correct way to do it.
I'm doing some background processing in my activity and have a ListView that shows the progress. I 'update' the listView with
adapter.notifyDataSetChanged();
However when I leave the activity and then come back, the background processes are still running, but the list view isn't updated. This is presumably because it's a new object, not the previous one. How do I maintain my list view object between activity loads?
This is my activity. I think the issue is that the 'adapter' variable that the download uses to bind to to show updates, is recreated in the onCreate method of the activity, and the 'adapter' variable that the download originally bound to is not in the activity anymore.
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.model.ProgressEvent;
import com.amazonaws.services.s3.model.ProgressListener;
import com.amazonaws.services.s3.transfer.TransferManager;
//import com.amazonaws.auth.AWSCredentials;
//import com.amazonaws.auth.BasicAWSCredentials;
public class VideosActivity extends Activity {
ListView video_list;
CustomList adapter;
File storage_dir;
SharedPreferences completed_downloads; //http://developer.android.com/guide/topics/data/data-storage.html
SharedPreferences downloaded_data; //maps position to percent downloaded
SharedPreferences queue; //holds which fiiles are awaiting download
String images[]; //holds references to all thumnails for vids
String volume; //something like vol1 or vol2
String s3_dir; //the directory after the boucket that the files are stored in (do not add first slash)
String s3_bucket = "com--apps";
Handler handler = new Handler(); //'tunnel' through whci other threads communicate with main thread
Map<String, String[][]> video_config = new HashMap<String, String[][]>(); //holds info about video thumbs and filenames for all apps
ArrayList<String> arr_videos = new ArrayList<String>(); //holds video names
DownloadQueue queue_manager = new DownloadQueue();
#Override
public void onCreate(Bundle savedInstanceState) {
Log.v("dev", "onCreateCalled");
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
volume = getPackageName().split("\\.")[2]; //something like vol1 or vol2
s3_dir = "android/" + volume + "/"; //the directory after the boucket that the files are stored in (do not add first slash)
completed_downloads = getSharedPreferences("completed_downloads", 0);
downloaded_data = getSharedPreferences("downloaded_data", 0);
queue = getSharedPreferences("queue", 0);
storage_dir = getApplicationContext().getExternalFilesDir(null); //private to app, removed with uninstall
adapter = new CustomList(this, R.layout.customlist, arr_videos);
video_list = (ListView)findViewById(R.id.list);
video_list.setAdapter(adapter); //set adapter that specifies list contents
ensureStorageDirExists( storage_dir ); //make sure storage dir exists
set_video_data(); //store vid dat in array
ensure_connection_or_warn();
}
public boolean ensure_connection_or_warn()
{
if(have_connection())
{
return true;
}
else
{
Toast.makeText(this, "No Internet connection", Toast.LENGTH_LONG).show();
return false;
}
}
protected void ensureStorageDirExists( File dir )
{
if (!dir.exists())
{
dir.mkdirs();
}
}
public void set_video_data()
{
config_video_data(); //run config
images = video_config.get(getPackageName())[0]; //set images
for (String name : video_config.get(getPackageName())[1] ) { //set video info, this should be streamlined but is due to legacy code and my crap Java skills, consider doing like this: http://developer.android.com/guide/topics/resources/more-resources.html#TypedArray
arr_videos.add(name);
}
}
public SharedPreferences stored_vals()
{
return PreferenceManager.getDefaultSharedPreferences(this);
}
public boolean have_connection()
{
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if(cm.getActiveNetworkInfo()!=null && cm.getActiveNetworkInfo().isConnected() && cm.getActiveNetworkInfo().isAvailable())
{
Log.v("dev", "have internet connection");
return true;
}
else
{
Log.v("dev", "No internet connection");
return false;
}
}
public class DownloadQueue
{
protected void process()
{
if (queue.size() > 0 && queue.get(0).download_status == "queued") //this is meant to force one download at a time
{
queue.get(0).start();
adapter.notifyDataSetChanged();
}
}
protected void add(Integer position)
{
queue.edit.putInt(position+"");
d.download_status = "queued";
adapter.notifyDataSetChanged();
}
protected boolean position_is_queued(Integer position)
{
for (Download d : queue ) {
if(d.position == position)
{
return true;
}
}
return false;
}
protected void remove(Download d)
{
queue.remove(d);
adapter.notifyDataSetChanged();
}
}
public class CustomList extends ArrayAdapter<String>
{
View view;
int position;
Button btn;
public CustomList(Context context, int layout_id, ArrayList<String> objects)
{
super(context, layout_id, objects);
}
#Override
public View getView(final int position, View convertView, ViewGroup view_group)
{
set_view(convertView);
this.position = position;
TextView text_view = (TextView) view.findViewById(R.id.name);
ImageView image = (ImageView) view.findViewById(R.id.img);
btn = (Button) view.findViewById(R.id.play);
prepare_btn();
text_view.setText( list_text() );
image.setImageResource(
getResources().getIdentifier(images[position], "drawable", getPackageName())
);
return view;
}
public String list_text()
{
String s = arr_videos.get( position ).replace("_", " ").replace(".m4v", "");
s = s.substring(2, s.length());
return s;
}
public void set_view(View convertView)
{
if(convertView == null)
{
LayoutInflater inflater = getLayoutInflater();
view = inflater.inflate(R.layout.customlist, null);
}
else
{
view = convertView;
}
}
public Boolean is_downloaded()
{
return completed_downloads.getBoolean(position + "", false);
}
public void prepare_btn()
{
btn.setTag((Integer) position);
if(is_downloaded() == true)
{
btn.setText("Play ");
btn.setEnabled(true);
btn.setOnClickListener( new OnClickListener()
{
public void onClick(View btn)
{
int position = (Integer) btn.getTag();
Intent i = new Intent(VideosActivity.this, PlayVideoActivity.class);
String video_path = storage_dir + "/" + arr_videos.get(position);
Log.v("video_path", video_path);
i.putExtra("video_path", video_path);
startActivity(i);
}
});
}
else if( downloaded_data.contains(position+"") ) //it it's currently being downloaded
{
btn.setText(downloaded_data.getInt(position+"", 0) + "%");
btn.setEnabled(false);
}
else if( queue_manager.position_is_queued(position) ) //it's in the queue
{
btn.setText("Queued");
btn.setEnabled(false);
}
else
{
btn.setText("Download");
btn.setEnabled(true);
btn.setOnClickListener( new OnClickListener()
{
public void onClick(View btn)
{
int position = (Integer) btn.getTag();
btn.setEnabled(false);
queue_manager.add(position);
}
});
}
}
}
public class Download
{
File new_video_file;
int position;
String download_status;
com.amazonaws.services.s3.transfer.Download download;
protected void queue(int position)
{
this.position = position;
queue_manager.add(this);
queue_manager.process();
//put this download in the queue
//start downloading if it's the only one in the queue
}
protected void start()
{
if(!ensure_connection_or_warn())
{
return;
}
this.download_status = "started";
this.new_video_file = new File(storage_dir, arr_videos.get(position)); //local file to be writtent to
TransferManager tx = new TransferManager(credentials);
//http://stackoverflow.com/questions/6976317/android-http-connection-exception
this.download = tx.download(s3_bucket, s3_dir + arr_videos.get(position), new_video_file);
download.addProgressListener(new ProgressListener()
{
public void progressChanged(final ProgressEvent pe)
{
handler.post( new Runnable()
{
#Override
public void run()
{
if ( pe.getEventCode() == ProgressEvent.COMPLETED_EVENT_CODE )
{
Download.this.onComplete();
}
else
{
Download.this.onProgressUpdate();
}
}
});
}
});
}
//protected void onProgressUpdate(Double progress)
protected void onProgressUpdate()
{
this.download_status = "downloading";
Double progress = this.download.getProgress().getPercentTransfered();
Integer percent = progress.intValue();
//Log.v("runnable", percent + "");
downloaded_data.edit().putInt(position+"", percent).commit();
adapter.notifyDataSetChanged();
}
protected void onComplete()
{
Log.v("dev", "download complete!!!");
//downloaded_data.remove(position);
this.download_status = "complete";
completed_downloads.edit().putBoolean(position + "", true).commit();
queue_manager.remove(this);
queue_manager.process();
adapter.notifyDataSetChanged();
// this.download.abort();
}
}
}
Not exactly sure what happens during background processing and what do you mean by ListView state, but my suggestion would be:
try the following:
#Override
protected void onResume() {
super.onResume();
yourAdapter.clear();
yourAdapter.addAll(yourData); // API level [1..10] use for(..){ yourAdapter.add(yourData.get(index)) }
yourAdapter.notifyDataSetChanged();
}
Reason:
An adapter keeps a copy of all the elements, so when you call notifyDataSetChanged, it checks its own copy of the elements
I'm trying to start another activity in my main activity using this method:
public void switchToRead(){// Switches to the reading view which displays the text that the tts engine reads off.
Intent intent = new Intent(getApplicationContext(),ReadOut.class);
intent.putExtra("response", res);
startActivity(intent);
}
This starts the following class:
package com.example.webview;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.speech.tts.TextToSpeech;
import android.text.method.ScrollingMovementMethod;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class ReadOut extends Activity implements TextToSpeech.OnInitListener, OnClickListener {
boolean paused = false;
String leftToRead = null;
String res = null;
TextToSpeech tts;
protected void onPreExecute()
{
System.out.println("Pre-execute");
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.read_out);
Intent intent = getIntent();
res = intent.getExtras().getString("response");
TextView textv = (TextView) findViewById(R.id.textView1);
textv.setText(res);
textv.setMovementMethod(new ScrollingMovementMethod());
android.view.Display display = ((android.view.WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
textv.setHeight((int)(display.getHeight()*0.76));
System.out.println("START");
tts = new TextToSpeech(this, this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
return true;
}
public String speakFull(String text){
System.out.println("Speaking: " + text);
System.out.println("Speaking");
String[] sentences = text.split("\n|\\.(?!\\d)|(?<!\\d)\\."); // Regex that splits the body of text into the sentences of that body which are stored in a String array.
for(int i = 0; i < sentences.length; i++){
if(!tts.isSpeaking() && !paused){
System.out.println("Speaking: " + i);
tts.speak(sentences[i], TextToSpeech.QUEUE_FLUSH, null);
}else if(paused){
System.out.println("Paused");
String paused = "";
int k = 0;
if(i != 0){
k = i-1;
}
leftToRead = null;
for(int j = k; j < sentences.length; j++){
leftToRead += sentences[j];
}
return leftToRead;
}else{
i--;
System.out.println("Sleeping");
System.out.println("Speaking : " + tts.isSpeaking());
try {
Thread.sleep(1000);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
if(i == sentences.length - 1){
return "Message 001: Complete";
}
}
return null;
}
#Override
public void onInit(int arg0) {
System.out.println("speakFull");
leftToRead = speakFull(res);
}
public void clickPause(View v){
if(paused){
paused = false;
Button b = (Button) findViewById(R.id.button1);
b.setText("Play");
}else{
paused = true;
Button b = (Button) findViewById(R.id.button1);
b.setText("Pause");
if(leftToRead == null){
leftToRead = speakFull(res);
}else{
leftToRead = speakFull(leftToRead);
}
}
}
#Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
}
}
After the ReadOut class is started one of a couple things can happen,
either the screen turns black, the text to speech begins reading, and the app is telling me it's not responding, OR it shows me the view for ReadOut, reads in text to speech, and then tells me it's not responding.
I'm really confused as to why this is happening, and any insight would be appreciated.
I don't know anything about using TTS but I can tell you that this line is probably causing a problem
Thread.sleep(1000);
It appears you are calling it on the UI Thread which isn't a good idea. You need to use a background Thread and update it with something like runOnUiThread() or AsyncTask or you could use a Handler.