i use this (link or code) to store id and password of user
http://techblogon.com/android-login-registration-screen-with-sqlite-database-example/
problem is i want to store list view item permanently in my listview when user login against their account
private static int RESULT_LOAD_IMAGE = 1;
private String currentImageName = "ic_launcher";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_ad_layout);
Button saveButton = (Button) findViewById(R.id.buttonSaveAdd);
saveButton.setOnClickListener(this);
Button buttonaddimage = (Button) findViewById(R.id.buttonAddImage);
buttonaddimage.setOnClickListener(this);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want Create a new Add?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
Intent intent = new Intent(Create_adds_Activity.this, Button_mak.class);
startActivity(intent);
}
});
builder.show();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonAddImage:
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
break;
case R.id.buttonSaveAdd:
EditText editTextTitle = (EditText) findViewById(R.id.editTextTitle);
EditText editTextDes = (EditText) findViewById(R.id.editTextDescription);
EditText editTextOwner = (EditText) findViewById(R.id.editTextOwnerName);
EditText editTextOwnerEmail = (EditText) findViewById(R.id.editTextOwnerEmail);
EditText editTextPrice = (EditText) findViewById(R.id.editTextPrice);
//populating data object from the values received
//from view
String title = editTextTitle.getText().toString();
String description = editTextDes.getText().toString();
String ownerName = editTextOwner.getText().toString();
String ownerEmail = editTextOwnerEmail.getText().toString();
String pricce = editTextPrice.getText().toString();
Advertisement object = new Advertisement(title, description,
ownerName, ownerEmail, currentImageName, Integer.parseInt(pricce), 100);
Button_mak.ads.add(object);
this.finish();
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView10 = (ImageView) findViewById(R.id.creatae);
imageView10.setImageBitmap(BitmapFactory.decodeFile(picturePath));
currentImageName = ">>>"+picturePath;
}
i use array adapter
final Context context = this;
public static ArrayList<Advertisement> ads = new ArrayList<Advertisement>();
I would deffenitely recommend using SQLite to save your data.
In the beginning it might seem a bit complex, but when ur used to it, its an ease.
Here's a handy little tutorial: http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/
Related
This is my code and when i run the code then output will be "**you haven't picked images"**
sdk which i use currently in this app
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.example.letsget.humanitysavior"
minSdkVersion 21
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
Here is the manifests permissions
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.RECORD_AUDIO" />
Here is the fragment code
public class NewPostPublicFragment extends Fragment {
public NewPostPublicFragment() {
// Required empty public constructor
}
private int PICK_IMAGE_MULTIPLE = 3;
String imageEncoded;
List<String> imagesEncodedList;
private GridView gvGallery;
private NewPostImagesAdapter galleryAdapter;
CarouselView carouselView;
private ArrayList<Uri> mArrayUri;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_new_post_public, container, false);
gvGallery = view.findViewById(R.id.gridview);
ImageView selectimgicon = view.findViewById(R.id.selectimgicon);
ImageView selectvideoicon = view.findViewById(R.id.selectvideoicon);
ImageView selectcameraicon = view.findViewById(R.id.selectcameraicon);
carouselView = view.findViewById(R.id.carouselview);
final TextInputEditText postcategories = view.findViewById(R.id.postcategories);
//carouselView.setPageCount(mThumbIds.length);
//carouselView.setImageListener(imageListener);
//for image selection
selectimgicon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//LOGIC FOR PROFILE PICTURE
selectImagesFromGallery();
}
});
postcategories.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final CharSequence[] items = { "Book", "Cloth", "Electronic", "Furniture", "Bag", "Social Post", "Other" };
AlertDialog.Builder postCategoryBuilder = new AlertDialog.Builder(v.getContext(),AlertDialog.THEME_HOLO_LIGHT);
postCategoryBuilder.setTitle("Select Post Category");
postCategoryBuilder.setIcon(R.mipmap.categoryicon);
postCategoryBuilder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// the user clicked on colors[which]
postcategories.setText(items[which]);
}
});
postCategoryBuilder.show();
}
});
return view;
}
ImageListener imageListener = new ImageListener() {
#Override
public void setImageForPosition(int position, ImageView imageView) {
//imageView.setImageResource(mThumbIds[position]);
imageView.setImageURI(mArrayUri.get(position));
}
};
private void selectImagesFromGallery() {
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Image"), PICK_IMAGE_MULTIPLE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
Log.v(TAG, "requestCode=" + requestCode + ", resultCode = "+ resultCode + ", data = " + data);
// When an Image is picked
if (requestCode == PICK_IMAGE_MULTIPLE && resultCode == RESULT_OK && data != null) {
// Get the Image from data
String[] filePathColumn = { MediaStore.Images.Media.DATA };
imagesEncodedList = new ArrayList<String>();
if(data.getData()!=null){
Uri mImageUri = data.getData();
// Get the cursor
Cursor cursor = getActivity().getContentResolver().query(mImageUri,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imageEncoded = cursor.getString(columnIndex);
cursor.close();
ArrayList<Uri> mArrayUri = new ArrayList<Uri>();
mArrayUri.add(mImageUri);
galleryAdapter = new NewPostImagesAdapter(getActivity().getApplicationContext(),mArrayUri);
gvGallery.setAdapter(galleryAdapter);
gvGallery.setVerticalSpacing(gvGallery.getHorizontalSpacing());
ViewGroup.MarginLayoutParams mlp = (ViewGroup.MarginLayoutParams) gvGallery
.getLayoutParams();
mlp.setMargins(0, gvGallery.getHorizontalSpacing(), 0, 0);
carouselView.setPageCount(mArrayUri.size());
carouselView.setImageListener(imageListener);
} else {
if (data.getClipData() != null) {
ClipData mClipData = data.getClipData();
ArrayList<Uri> mArrayUri = new ArrayList<Uri>();
for (int i = 0; i < mClipData.getItemCount(); i++) {
ClipData.Item item = mClipData.getItemAt(i);
Uri uri = item.getUri();
mArrayUri.add(uri);
// Get the cursor
Cursor cursor = getActivity().getContentResolver().query(uri, filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imageEncoded = cursor.getString(columnIndex);
imagesEncodedList.add(imageEncoded);
cursor.close();
galleryAdapter = new NewPostImagesAdapter(getActivity().getApplicationContext(),mArrayUri);
gvGallery.setAdapter(galleryAdapter);
gvGallery.setVerticalSpacing(gvGallery.getHorizontalSpacing());
ViewGroup.MarginLayoutParams mlp = (ViewGroup.MarginLayoutParams) gvGallery
.getLayoutParams();
mlp.setMargins(0, gvGallery.getHorizontalSpacing(), 0, 0);
}
Log.v("LOG_TAG", "Selected Images" + mArrayUri.size());
}
}
} else {
Toast.makeText(getContext(), "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(getContext(), "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
}
when I run this app and tap on image button then it open the gallery and select the images after that when i press the done button then it's not display images it just display toast message you haven't picked images
Check these Steps:
Give permission to use camera in AndroidManifest.xml
Use this code to get image properly
String RequestCode=123;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == RequestCode && resultCode== RESULT.OK){
//Here get your image code
}
}
Also Check Toast in your OnActivityResult() method and check if condition is true or false. Probably your if condition is false that's why image is not received from gallery.
I am creating my first project using Android Studio, I am aiming to create an app where you can load photos in from the phones memory and display them so people can see.
I've managed to get it working sort of how I want it to, the pictures in the gallery stay where they should do when I close out of the app and then reopen it - however if I close the app restart it and then try and add a new photo it overwrites the gallery and deletes the pictures I orginally put in. Does anyone have any ideas on how I can fix this? I tried playing with when I create the images ArrayList but that didn't help.
Code:
Main Activity
public class MainActivity extends AppCompatActivity {
private static final int PERMISSION_REQUEST = 0;
private static final int RESULT_LOAD_IMAAGE = 1;
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String Name = "nameKey";
ImageView imageView;
Button uploadButton;
Button savedPhotos;
List<String> images;
String imageCreated;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED){
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST);
}
imageView = (ImageView) findViewById(R.id.imageView);
uploadButton = (Button) findViewById(R.id.button);
savedPhotos = (Button) findViewById(R.id.button2);
SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
images = new ArrayList<>();
uploadButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAAGE);
SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(imageCreated, "Complete");
}
});
savedPhotos.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openPage2();
}
});
}
public void openPage2()
{
Intent intent = new Intent(this, SavedPhotos.class);
startActivity(intent);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch(requestCode)
{
case PERMISSION_REQUEST:
if(grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(this, "Permission Not Granted", Toast.LENGTH_SHORT).show();
finish();
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
switch(requestCode)
{
case RESULT_LOAD_IMAAGE:
if(resultCode == RESULT_OK)
{
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
images.add(picturePath);
StringBuilder stringBuilder = new StringBuilder();
for(String i : images)
{
stringBuilder.append(i);
stringBuilder.append(",");
}
SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("images", stringBuilder.toString() );
editor.commit();
}
}
}}
And SavedPhotos
public class SavedPhotos extends AppCompatActivity {
public static final String MyPREFERENCES = "MyPrefs" ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_saved_photos);
SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
String wordsString = sharedpreferences.getString("images", "");
String[] itemWords = wordsString.split(",");
List<String> items = new ArrayList<String>();
LinearLayout layout = (LinearLayout) findViewById(R.id.linear);
for(int i = 0; i < itemWords.length; i++) {
ImageView imageView = new ImageView(this);
imageView.setId(i);
imageView.setPadding(2, 2, 2, 2);
imageView.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher_foreground));
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
layout.addView(imageView);
items.add(itemWords[i]);
imageView.setImageBitmap(BitmapFactory.decodeFile(items.get(i)));
}
}}
Thank you for your help :)
I actually run to same issues before until i met a well made library and requires nothing and made my code much good looking, FastSave: https://github.com/yehiahd/FastSave-Android.
I'm trying to take a photo from gallery on a Dialog but I couldn't. I cannot call startActivityResult() method to override on Dialog. Does anybody know a way to do it on Dialog?
Here is my code. (I need to do it in buttonG.setOnClickListener())
public class AddBirthdayDialog extends Dialog {
private Context context;
String name;
String sname;
private int day;
private int month;
private int year;
private byte[] imageByte;
private Bitmap imageBitmap;
private int RESULT_LOAD_IMAGE = 1;
final EditText textName;
final EditText textSname;
final DatePicker birthDate;
private DB myDB;
private SQLiteDatabase database;
private Person person = new Person();
public AddBirthdayDialog(final Context context) {
super(context);
this.context = context;
setCanceledOnTouchOutside(false);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.addbirthday_layout);
myDB = new DB(context);
textName = (EditText) findViewById(R.id.editTextname);
textSname = (EditText) findViewById(R.id.editTextsname);
birthDate = (DatePicker) findViewById(R.id.datePicker);
Button buttonG = (Button) findViewById(R.id.buttonUploadG);
buttonG.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
**//Need to call gallery and take a photo's bitmap or byte[] here.**
}
});
Button buttonC = (Button) findViewById(R.id.buttonUploadC);
buttonC.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
Button cancelButton = (Button) findViewById(R.id.cancelbutton);
cancelButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dismiss();
}
});
Button save = (Button) findViewById(R.id.buttonadd);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name = textName.getText().toString();
sname = textSname.getText().toString();
day = birthDate.getDayOfMonth();
month = birthDate.getMonth()+1;
year = birthDate.getYear();
final String dayStr = String.valueOf(day);
final String monthStr = String.valueOf(month+1);
final String yearStr = String.valueOf(year);
person.setName(name);
person.setSname(sname);
person.setDay(day);
person.setMonth(month);
person.setYear(year);
person.setDateStr(dayStr + "/" + monthStr + "/" + yearStr);
myDB.addBirthday(person);
if(context instanceof MainActivity)
((MainActivity)context).onResume();
dismiss();
}
});
}
}
Thanks in advance :)
inside your class:
#SuppressLint("NewApi")
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case SELECTED_PICTURE:
if (resultCode == RESULT_OK) {
Uri uri = data.getData();
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri, projection,
null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(projection[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
selectedImage = BitmapFactory.decodeFile(filePath);
d = new BitmapDrawable(selectedImage);
iv.setBackground(d);
update.setVisibility(View.VISIBLE);
}
break;
}
}
inside onClick:
Intent i = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, SELECTED_PICTURE);
Global variables:
private static final int SELECTED_PICTURE = 1;
Bitmap selectedImage;
What is context? If it is an activity, you can to start activity from your context-activity and handle onActivityResult in context-activity
package com.example.address_book;import android.app.Activity;import android.content.Intent;import android.database.Cursor;import android.net.Uri;import android.os.Bundle;import android.provider.ContactsContract.CommonDataKinds.Phone;import android.view.Menu;import android.view.View;import android.view.View.OnClickListener;import android.widget.ImageButton;import android.widget.Toast;
public class MainActivity extends Activity {
private static final int PICK_CONTACT_REQUEST = 1;
String[] num={" "," "};
String number1;
#Overrideprotected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try{ImageButton add_me = (ImageButton) findViewById(R.id.imageButton1);
add_me.setOnClickListener(new OnClickListener(){
public void onClick(View v){
Intent pickContactIntent = new Intent(Intent.ACTION_PICK, Uri.parse("content://contacts"));
pickContactIntent.setType(Phone.CONTENT_TYPE);startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST);
}
});
}catch (Exception e) {
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data){
int n=0;int n1=0;
if (requestCode == PICK_CONTACT_REQUEST){
if (resultCode == RESULT_OK){
Uri stuff = data.getData();Intent in = new Intent(android.content.Intent.ACTION_VIEW, stuff);
in.setType("text/x-vcard");
startActivity(in);
String[] projection = {Phone.NUMBER};Cursor cursor = getContentResolver().query(stuff, projection, null, null, null);cursor.moveToFirst();
int column = cursor.getColumnIndex(Phone.NUMBER);
number1 = cursor.getString(column);
n++;number1 = number1.replace("-" ,"");
for(int i=0;i<num.length;i++){num[i]=number1;
}
}
}
}
#Overridepublic boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.main, menu);return true;
}
}
Try with this dude it will open your contact jusr pass contactId in this
Intent intent = new Intent(Intent.ACTION_VIEW);
//pass your contact id
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI, String.valueOf(contactId));
intent.setData(uri);
mcntxt.startActivity(intent);
simple program: 2 buttons (previous/next) and a textview to show text.
by intent I created an Index (inside a method)
private void index(){
Intent i = new Intent(this, Index.class);
startActivityForResult(i, 1);
}
Index.class (with 3 buttons):
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String result = "1";
Intent returnIntent = new Intent();
returnIntent.putExtra("result",result);
setResult(RESULT_OK,returnIntent);
finish();
}
});
Main.class
String value = "1";
final String prog1[] = new String[16];
final String prog2[] = new String[105];
final String prog3[] = new String[66];
int a;
int b;
int c=3;
int array1start = 0; int array1end = 15;
int array2start = 0; int array2end = 105;
int array3start = 0; int array3end = 65;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
if (value.equals("1")){
a = array1start;
b = array1end;
prog=prog1;
}
else if (value.equals("2")){
a = array2start;
b = array2end;
prog=prog2;
textView1.setText(""+prog[a]);
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == RESULT_OK){
String result=data.getStringExtra("result");
value=result;
Toast toast2=Toast.makeText(this,"value: "+value,Toast.LENGTH_LONG);
toast2.show();
}
if (resultCode == RESULT_CANCELED) {
//Write your code on no result return
}}
}//onAcrivityResult
at this point, choosen choice in index class should be change a result string to "value" string in main class
private void index(){
Intent i = new Intent(this, Index.class);
startActivityForResult(i, 1);
}
my textview take data from array1 or array2 by index class
so, I dont' understand how update textview (because index value is correct).
thanks for the help
Put you code into function onActivityResult
if (value.equals("1")){
a = array1start;
b = array1end;
prog=prog1;
}
else if (value.equals("2")){
a = array2start;
b = array2end;
prog=prog2;
textView1.setText(""+prog[a]);