I'm a beginner on Android Studio, and java, i want to create a random background of view images, i try to use this How To Display Random images on image view , but not working, this code doesn't generate any image
Please, can someone help me to resolve this code or to create another code to random background.
I use this code to generate images
final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.rnd_images);
final ImageView img = (ImageView) findViewById(R.id.imgRandom);
// I have 3 images named img_0 to img_2, so...
final String str = "img_" + rnd.nextInt(2);
img.setImageDrawable
(
getResources().getDrawable(getResourceID(str, "drawable",
getApplicationContext()))
);
}
protected final static int getResourceID
(final String resName, final String resType, final Context ctx)
{
final int ResourceID =
ctx.getResources().getIdentifier(resName, resType,
ctx.getApplicationInfo().packageName);
if (ResourceID == 0)
{
throw new IllegalArgumentException
(
"No resource string found with name " + resName
);
}
else
{
return ResourceID;
}
}
}
Related
I would like to enter multiple text fields for example
name
email
password
address
And then I would like to generate a QR code from this input. How can I do that in android studio?
Setting up the library and manifest
Open App level gradle file and import the library.
implementation 'androidmads.library.qrgenearator:QRGenearator:1.0.3'
The, click “Sync Now”.
Then, open your Manifest file and add the following permissions. It is used to save QR Code to file storage.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
We need to handle runtime permissions from Android Version 6.0.
Generating QR Code
QRGEncoder qrgEncoder = new QRGEncoder(inputValue, null, QRGContents.Type.TEXT, smallerDimension);
Here, inputValue is an input to be converted to QR Code.
Input Type also can be specified while initializing the library.
We can specify the dimensions also.
Then, add the following lines to create QR Code and encode that into Bitmap Format.
try {
// Getting QR-Code as Bitmap
bitmap = qrgEncoder.encodeAsBitmap();
// Setting Bitmap to ImageView
qrImage.setImageBitmap(bitmap);
} catch (WriterException e) {
Log.v(TAG, e.toString());
}
qrImage is an ImageView used to preview the generated QR code bitmap.
Saving QR Code
QR Generator has an option to save the generated QR Code Bitmap to storage using the following lines.
// Save with location, value, bitmap returned and type of Image(JPG/PNG).
QRGSaver.save(savePath, edtValue.getText().toString().trim(), bitmap, QRGContents.ImageType.IMAGE_JPEG);
We can save QR Code in PNG & JPG format also. We have to handle runtime permissions from Android version 6.0.
Your particular case:
Combine the information you want to encode in the QR code, and add it as the inputValue for the QRGEncoder. Here is an example code for clarity:
public class MainActivity extends AppCompatActivity {
String TAG = "GenerateQRCode";
EditText edtValue;
ImageView qrImage;
Button start, save;
String inputValue;
String savePath = Environment.getExternalStorageDirectory().getPath() + "/QRCode/";
Bitmap bitmap;
QRGEncoder qrgEncoder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
qrImage = (ImageView) findViewById(R.id.QR_Image);
edtValue = (EditText) findViewById(R.id.edt_value);
start = (Button) findViewById(R.id.start);
save = (Button) findViewById(R.id.save);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
inputValue = edtValue.getText().toString().trim();
if (inputValue.length() > 0) {
WindowManager manager = (WindowManager) getSystemService(WINDOW_SERVICE);
Display display = manager.getDefaultDisplay();
Point point = new Point();
display.getSize(point);
int width = point.x;
int height = point.y;
int smallerDimension = width < height ? width : height;
smallerDimension = smallerDimension * 3 / 4;
qrgEncoder = new QRGEncoder(
inputValue, null,
QRGContents.Type.TEXT,
smallerDimension);
try {
bitmap = qrgEncoder.encodeAsBitmap();
qrImage.setImageBitmap(bitmap);
} catch (WriterException e) {
Log.v(TAG, e.toString());
}
} else {
edtValue.setError("Required");
}
}
});
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean save;
String result;
try {
save = QRGSaver.save(savePath, edtValue.getText().toString().trim(), bitmap, QRGContents.ImageType.IMAGE_JPEG);
result = save ? "Image Saved" : "Image Not Saved";
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
Article: https://www.c-sharpcorner.com/article/how-to-generate-qr-code-in-android/
Concatenate all the information in a string and do a hash on said string. Next use a library such as (https://github.com/zxing/zxing) to generate the QR code.
Use this for generating qr code online. Then use picasso to load the image. ( Use your data in the url parameter )
https://chart.googleapis.com/chart?chs=500x500&cht=qr&chl=data
I found it as the best way.
What I want to do: get the id of the src of an ImageView, compare it to the ids of two drawables, and swap them, using AsyncTask (just because I want to understand how it works).
I've read similar questions here, and so far this is what I've got:
public class Main extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView image = (ImageView) findViewById(R.id.img);
Integer integer = (Integer) image.getTag();
}
private class cambiarImagen extends AsyncTask<Integer, Integer, Integer> {
protected void onPreExecute() {
ImageView image = (ImageView) findViewById(R.id.img);
Integer integer = (Integer) image.getTag();
int img1 = R.drawable.zapato;
int img2 = R.drawable.zapatod;
}
#Override
protected Integer doInBackground(Integer... values) {
// parte logica
int num = values[0];
int zapato = values[1];
int zapatod = values[2];
if (num == zapato) {
num = zapatod;
} else if (num == zapatod) {
num = zapato;
}
return num;
}
protected Void onPostExecute(Integer... values) {
int num = values[0];
ImageView image = (ImageView) findViewById(R.id.img);
image.setTag(num);
return null;
}
}
Of course this doesn't work.
1. I don't understand how to get the id of the drawable that ImageView has as its src.
2. I don't understand how the params are passed in AsyncTask; onPreExecute should receive the UI stuff, doInbackground should receive it to compare it and return the drawable int that should be set to the ImageView, and onPreExecute should set it to the ImageView.
I don't understand how to get the id of the drawable that ImageView has as its src.
I haven't had to do this so may not work but you should be able to use
imageView.getDrawable().getId();
I don't understand how the params are passed in AsyncTask;
Whatever you pass in task.execute() is received by doInBackground(). If you call publishProgress() then whatever params are sent there are received by onProgressUpdate(). And the data returned in doInBackground() is received by onPostExecute().
AsyncTask, just so you know, shouldn't be needed for this but I know you said you wanted to learn how to use it. I was a little confused on exactly what specifically you were having trouble with besides these two things so please elaborate if I missed something.
ImageView Docs
AsyncTask Docs
AsyncTask Example (in case it can be helpful)
You should do other task if you like to get to learn ASyncTask.
I would have done a dialog with progress bar or something instead if i wanted to learn ASyncTask.
edit:
As Samus Arin comment on the main post about you should always have track on which image that you are showing. so instead use something like
if(currentImage == R.Drawable.image1){
image.setImageResource(R.Drawable.image2);
}else{
image.setImageResource(R.Drawable.image1);
}
For what it's worth, take a look at what I'm doing with an AsyncTask, maybe it'll give ya some ideas.
This is Monodroid/C# code, not raw Java/Android (but the syntax is extremely close). As such, inner-classes do not get an implicit reference to their containing object, and so I pass one in (called outer in the constructor). I chose to name it "_" as a lexicographical extension to .NET's _member naming convention for private data members.
public class MonthChangeTask : AsyncTask
{
private CalendarView _; // outer class
private DateTime _newMonth;
private bool _refreshInspectionRecordsRemote;
private bool _changingInspector;
private bool _todayButtonPressed;
private Android.App.ProgressDialog _progressDialog;
private IMXController _controller;
private Dictionary<string, string> _paramz;
private DateTime _newSelectedDate;
public MonthChangeTask( CalendarView outer, DateTime newMonth, bool changingInspector, bool refreshInspectionRecordsRemote, bool todayButtonPressed )
{
_ = outer;
_newMonth = newMonth;
_changingInspector = changingInspector;
_refreshInspectionRecordsRemote = refreshInspectionRecordsRemote;
_todayButtonPressed = todayButtonPressed;
}
protected override void OnPreExecute()
{
base.OnPreExecute();
_progressDialog = Android.App.ProgressDialog.Show( _ , "", "Loading Inspections...");
_newSelectedDate = _._calendar.SetMonth(new DateTime(_newMonth.Year, _newMonth.Month, 1));
AppSettingService.SetCalendarDate(_newMonth);
_paramz = new Dictionary<string, string>();
string target = MD.MxNAVIGATION.CONTROLLER.CALENDAR._name;
string action = MD.MxNAVIGATION.CONTROLLER.ACTION.GET;
string command = _refreshInspectionRecordsRemote
? ((int) MD.MxNAVIGATION.CONTROLLER.CALENDAR.Command.RefreshInspectionRecordsRemote).ToString()
: ((int) MD.MxNAVIGATION.CONTROLLER.CALENDAR.Command.RefreshInspectionRecordsLocal).ToString();
string url = target + "/" + action + "/" + command;
_controller = MXContainer.Instance.GetController(url, ref _paramz);
}
protected override Java.Lang.Object DoInBackground(params Java.Lang.Object[] #params)
{
if ( _paramz == null )
{
Log.Info(FIDB.TAG_APP, "MonthChangeTask.DoInBackground(): paramz = NULL");
}
else
{
_controller.Load( _paramz );
}
return true;
}
protected override void OnPostExecute(Java.Lang.Object result)
{
base.OnPostExecute(result);
_progressDialog.Dismiss();
_.Model = (CalendarVM)_controller.GetModel();
if (_changingInspector)
{
_._calendar.PermitSwitch = _.Model.Buttons.PermitsVisible;
_._calendar.ComplaintSwitch = _.Model.Buttons.ComplaintsVisible;
_._calendar.ProjectSwitch = _.Model.Buttons.ProjectsVisible;
_._calendar.PeriodicInspectionSwitch = _.Model.Buttons.PeriodicInspectionsVisible;
}
_.UpdateCalendar(_.Model.Inspections);
if( _todayButtonPressed )
{
_._calendar.SelectedDate = _._calendar.CurrentDate;
}
else
{
_._calendar.SelectedDate = _newSelectedDate;
}
_._calendar.Invalidate();
AppSettingService.SetCalendarDate( _._calendar.SelectedDate );
if ( _.Model.IsParcelCacheDownloading )
{
AnimationTask task = new AnimationTask( _ );
task.Execute( new Java.Lang.Object[1] );
}
}
}
i have been looking for a while and could not find a solution for my problem. I am trying to set an imageView depending on the User logged in. The main problem is how do i rename R.drawable.stock into R.drawable.user1where the name of the imageView varies with the name of the user. I tried setting it to a string like String temp="R.drawable."+userNameStore; but did not have luck.
Here is what i am doing:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile);
SharedPreferences app_preferences =
PreferenceManager.getDefaultSharedPreferences(this);
String userNameStore =
app_preferences.getString("userNameStore", null);
String temp="R.drawable."+userNameStore;
TextView textName=(TextView) findViewById(R.id.username);
textName.setText("Username: "+ userNameStore);
ImageView image = (ImageView) findViewById(R.id.imageView1);
image.setImageResource(temp);
}
I use 2 methods in my utility class for this:
public static int getImageId(Context context, String imageName) {
return context.getResources().getIdentifier("drawable/" + imageName, null, context.getPackageName());
}
public static int getRawResourceId(Context context, String rawName) {
return context.getResources().getIdentifier("raw/" + rawName, null, context.getPackageName());
}
So if you have an image resource in your drawable folder named user1, you could get and use its ID like this:
imageView.setImageResource(getImageId(this, "user1"));
You can use getIdentier, for example:
getResources().getIdentifier("star_off", "string", getPackageName());
Check the documentation here
In your case it should be something like:
int resID = getResources().getIdentifier(temp, "drawable", getPackageName());
...
image.setImageResource(resID);
You can construct your string identifier like this...
int id = getResources().getIdentifier("name_of_resource", "id", getPackageName());
It's covered here
I've a dynamic image array which come through from database. And i just show image thumbnails at first screen and want to display full screen of same image array. The thing is that i want to pass the whole dynamic array to next screen. Actually i know how to use preferences in java. But i don't know how to pass the whole array with variables or something. Any ideas would be appreciate.
public class MerchantDetails extends GLCityActivity implements OnClickListener {
public static MerchantDetails instance;
private Gallery gallery;
private ImageView imView;
String Header, contentName;
DBManager gDatabase = new DBManager(this);
private ArrayList<Multimedia> mm;
private ImageViewAdapter iva;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(R.style.Theme_Translucent);
getWindow().requestFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.details);
instance = this;
initActivity(instance, " ");
try {
gDatabase.createDataBase();
} catch (IOException e) {
throw new Error("Unable to create database");
}
try {
gDatabase.openDatabase();
} catch (SQLiteException sqle) {
throw sqle;
}
settingLayout();
}
public void settingLayout() {
SharedPreferences preferences = getSharedPreferences(
Constants.DEFAUL_SHARE_DATA, 0);
Header = preferences.getString("SubName", "");
headerTxt = (TextView) findViewById(R.id.templateTopTitleTView);
headerTxt.setText(Header);
gallery = (Gallery) findViewById(R.id.gallery);
if (mm.isEmpty()) {
gallery.setVisibility(gallery.INVISIBLE);
} else {
gallery.setAdapter(iva);
gallery.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v,
int position, long id) {
SharedPreferences preferences = getSharedPreferences(
Constants.DEFAUL_SHARE_DATA, 0);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("ImagePosition", mm.get(position) + "");
editor.putInt("ImageLength", mm.size());
Intent viewer = new Intent(instance, GalleryViewer.class);
startActivityForResult(viewer, 0);
if (editor.commit()) {
}
}
});
}
}
private class ImageViewAdapter extends ArrayAdapter<Multimedia> {
private ArrayList<Multimedia> items;
public ImageViewAdapter(Context context, int textViewResourceId,
ArrayList<Multimedia> items) {
super(context, textViewResourceId, items);
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.image_list, null);
}
Multimedia info = items.get(position);
if (info != null) {
ImageView imView = (ImageView) v
.findViewById(R.id.rowlistIconIView);
String name = info.thumbnail;
String[] test = gDatabase.split(name, ".");
int resID = getResources().getIdentifier(test[0], "drawable",
getPackageName());
Log.v("Log", name + ";" + resID + ";" + test[0] + ";");
try {
imView.setImageResource(resID);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
return v;
}
}
}
Edited :
#Jeremy Edwards,thanks for your reply. I tried to do as you suggest but i found this error while i coded. I tried to use putExtra(String name,int[] value) but the error said The method putExtra(String name,boolean value) in the type Intent is not applicable for the arguments (String,Multimedia). Actually i already chose putExtra(String name,int[] value) from auto suggest box. wonder how it change back to (String name,int[] value) suddenly. Please check my code below.
private ArrayList<Multimedia> mm;
viewer.putExtra("ImagePosition",mm.get(position));
viewer.putExtra(String name,int[] value)
For the viewer Intent. Use Intent.put(name, "Id of the image").
Then in the viewer activity use getIntent().getIntExtra(name) to get that id back.
I'd advise against passing image data itself since android uses IPC "Shared memory" to pass data between the activity boundaries. It was meant to be lightweight.
The viewer activity should get the ID and then hit the DB for the full blown image you want. You shouldn't need to use preferences either to accomplish this since the Bundle inside the Intent object will carry the information you need.
From scanning through your code I think you are storing the images in ArrayList.
ArrayList is Serializable so you can use bundle to pass it to the next screen. You can use bundle's putSerializable method
Something like this
Bundle bundle = new Bundle();
bundle.putSerializable(<key>, <your serializable obj>);
then use the getSerializable() to get it back
I am experimenting with the android FaceDetector.
I need to use a bitmap file (faces.bmp is from a group photo) since I have not found a way to use the android camera in the android emulator.
But BitmapFactory.decodeFile returns null and the documentation only says it returns null if the bitmap could not be decoded. It is just a 24 bit .bmp file. I am using Eclipse on Windows 7. Did I specify pathName incorrectly? Do I need to use something other than a 24 bit .bmp file?
public class MyFaces extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final int width = 600;
final int height = 600;
final int maxFaces = 8;
FaceDetector faceDetector = new FaceDetector(width, height, maxFaces);
String pathName = "../res/drawable-hdpi/faces.bmp";
try {
Bitmap bitmap = BitmapFactory.decodeFile(pathName);
Face faces[] = new Face[maxFaces];
int nFaces = faceDetector.findFaces(bitmap, faces);
Log.d(this.getClass().toString(), "Faces: " + nFaces);
} catch (Exception e) {
Log.e(this.getClass().toString(), e.getMessage(), e);
}
}
}
If you are just testing then in place of Bitmap bitmap = BitmapFactory.decodeFile(pathName); you could use:
Bitmap bitmap = BitmapFactory.decodeResource(R.drawable.faces);