stuck on loading image while trying to set image as wallpaper - java

i am creating images gallery wallpaper app in which i am trying to set image as wallpaper.
when i try to set a image as wallpaper i gets stuck at image loading message.
this is the screenshot: it gets stuck here:
tThis is the set wallpaper code:
set_wallpaper.java
package com.td.gridview;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.WallpaperManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class Set_Wallpaper extends Activity {
private Uri mImageCaptureUri;
private ImageView mImageView;
private AlertDialog dialog;
private static final int PICK_FROM_CAMERA = 1;
private static final int CROP_FROM_CAMERA = 2;
private static final int PICK_FROM_FILE = 3;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.set_wallpaper);
// get intent data
Intent i = getIntent();
// Selected image id
int position = i.getExtras().getInt("id");
ImageView ing = (ImageView) findViewById(R.id.image_page);
ing.setImageResource(MainActivity.ICONS[position]);
doCrop();
}
private void doCrop() {
final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();
/**
* Open image crop app by starting an intent
* ‘com.android.camera.action.CROP‘.
*/
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setType("image/*");
/**
* Check if there is image cropper app installed.
*/
List<ResolveInfo> list = getPackageManager().queryIntentActivities(
intent, 0);
int size = list.size();
/**
* If there is no image cropper app, display warning message
*/
if (size == 0) {
Toast.makeText(this, "Can not find image crop app",
Toast.LENGTH_SHORT).show();
return;
} else {
/**
* Specify the image path, crop dimension and scale
*/
intent.setData(mImageCaptureUri);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 200);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
intent.putExtra("return-data", true);
/**
* There is posibility when more than one image cropper app exist,
* so we have to check for it first. If there is only one app, open
* then app.
*/
if (size == 1) {
Intent i = new Intent(intent);
ResolveInfo res = list.get(0);
i.setComponent(new ComponentName(res.activityInfo.packageName,
res.activityInfo.name));
startActivityForResult(i, CROP_FROM_CAMERA);
} else {
/**
* If there are several app exist, create a custom chooser to
* let user selects the app.
*/
for (ResolveInfo res : list) {
final CropOption co = new CropOption();
co.title = getPackageManager().getApplicationLabel(
res.activityInfo.applicationInfo);
co.icon = getPackageManager().getApplicationIcon(
res.activityInfo.applicationInfo);
co.appIntent = new Intent(intent);
co.appIntent
.setComponent(new ComponentName(
res.activityInfo.packageName,
res.activityInfo.name));
cropOptions.add(co);
}
CropOptionAdapter adapter = new CropOptionAdapter(
getApplicationContext(), cropOptions);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose Crop App");
builder.setAdapter(adapter,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
startActivityForResult(
cropOptions.get(item).appIntent,
CROP_FROM_CAMERA);
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
if (mImageCaptureUri != null) {
getContentResolver().delete(mImageCaptureUri, null,
null);
mImageCaptureUri = null;
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
}
public class CropOption {
public CharSequence title;
public Drawable icon;
public Intent appIntent;
}
public class CropOptionAdapter extends ArrayAdapter<CropOption> {
private ArrayList<CropOption> mOptions;
private LayoutInflater mInflater;
public CropOptionAdapter(Context context, ArrayList<CropOption> options) {
super(context, R.layout.set_wallpaper, options);
mOptions = options;
mInflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup group) {
if (convertView == null)
convertView = mInflater.inflate(R.layout.set_wallpaper, null);
CropOption item = mOptions.get(position);
if (item != null) {
((ImageView) convertView.findViewById(R.id.image_page))
.setImageDrawable(item.icon);
((TextView) convertView.findViewById(R.id.tv_name))
.setText(item.title);
return convertView;
}
return null;
}
}
}
The following the code where i am swiping images and sending current showing image to set_wallpaper class on button click
SwipeActivity.java
package com.td.gridview;
import java.io.IOException;
import android.app.Activity;
import android.app.WallpaperManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
public class SwipeActivity extends Activity {
protected int curruntPosition;
protected int hh;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.swipe_view);
// get intent data
Intent i = getIntent();
// Selected image id
final int position = i.getExtras().getInt("id");
final ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
ImagePagerAdapter adapter = new ImagePagerAdapter();
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(position);
viewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
// Here you can set the wallpaper
curruntPosition = arg0;
if (curruntPosition == arg0) {
hh = 1;
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
//
Button bx = (Button) findViewById(R.id.xoom);
bx.setOnClickListener(new View.OnClickListener() {
public void onClick(View vx) {
// // TODO Auto-generated method stub
if (hh == 1) {
// Sending image id to FullScreenActivity
Intent i2 = new Intent(getApplicationContext(),
Full_Zoom.class);
// passing array index
i2.putExtra("id", curruntPosition);
startActivity(i2);
} else {
// get intent data
Intent i3 = getIntent();
// Selected image id
int position = i3.getExtras().getInt("id");
// Sending image id to FullScreenActivity
Intent i2 = new Intent(getApplicationContext(),
Full_Zoom.class);
// passing array index
i2.putExtra("id", position);
startActivity(i2);
}
}
});
//
// set wallpaper on button click
Button b1 = (Button) findViewById(R.id.wll);
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v2) {
// // TODO Auto-generated method stub
if (hh == 1) {
// Sending image id to FullScreenActivity
Intent i2 = new Intent(getApplicationContext(),
Set_Wallpaper.class);
// passing array index
i2.putExtra("id", curruntPosition);
startActivity(i2);
} else {
// get intent data
Intent i3 = getIntent();
// Selected image id
int position = i3.getExtras().getInt("id");
// Sending image id to FullScreenActivity
Intent i2 = new Intent(getApplicationContext(),
Set_Wallpaper.class);
// passing array index
i2.putExtra("id", position);
startActivity(i2);
}
}
});
}
public class ImagePagerAdapter extends PagerAdapter {
int[] icons = MainActivity.ICONS;
#Override
public int getCount() {
return icons.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = SwipeActivity.this;
ImageView imageView = new ImageView(context);
// int padding = context.getResources().getDimensionPixelSize(
// R.dimen.padding_large);
// imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
imageView.setImageResource(icons[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
}

Related

IndexOutOfBoundsException when making one Arraylist equal to another

I am trying to filter my RecyclerView using SearchView by following this guide: https://www.geeksforgeeks.org/searchview-in-android-with-recyclerview/
However, I am getting an IndexOutOfBoundsException when making one Arraylist equal to another, which I believe is happening at this portion of the code here:
public void filterList(ArrayList filteredlist) {
// below line is to add our filtered
// list in our course array list.
book_title = filteredlist;
// below line is to notify our adapter
// as change in recycler view data.
notifyDataSetChanged();
}
Here is the full code for my adapter class:
package com.benjamin.kwok.recipertracker;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> {
private Context context;
private Activity activity;
private ArrayList book_id, book_title, book_author, book_pages;
CustomAdapter(Activity activity, Context context, ArrayList book_id, ArrayList book_title, ArrayList book_author,
ArrayList book_pages){
this.activity = activity;
this.context = context;
this.book_id = book_id;
this.book_title = book_title;
this.book_author = book_author;
this.book_pages = book_pages;
}
public void filterList(ArrayList filteredlist) {
// below line is to add our filtered
// list in our course array list.
book_title = filteredlist;
// below line is to notify our adapter
// as change in recycler view data.
notifyDataSetChanged();
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.my_row, parent, false);
return new MyViewHolder(view);
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onBindViewHolder(#NonNull final MyViewHolder holder, final int position) {
holder.book_title_txt.setText(String.valueOf(book_title.get(position)));
holder.book_author_txt.setText(String.valueOf(book_author.get(position)));
holder.book_pages_txt.setText(String.valueOf(book_pages.get(position)));
//Recyclerview onClickListener
holder.mainLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, UpdateActivity.class);
intent.putExtra("id", String.valueOf(book_id.get(position)));
intent.putExtra("title", String.valueOf(book_title.get(position)));
intent.putExtra("author", String.valueOf(book_author.get(position)));
intent.putExtra("pages", String.valueOf(book_pages.get(position)));
activity.startActivityForResult(intent, 1);
}
});
}
#Override
public int getItemCount() {
return book_id.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView book_id_txt, book_title_txt, book_author_txt, book_pages_txt;
LinearLayout mainLayout;
MyViewHolder(#NonNull View itemView) {
super(itemView);
book_title_txt = itemView.findViewById(R.id.recipe_title_txt);
book_author_txt = itemView.findViewById(R.id.book_description_txt);
book_pages_txt = itemView.findViewById(R.id.recipe_pages_txt);
mainLayout = itemView.findViewById(R.id.mainLayout);
//Animate Recyclerview
Animation translate_anim = AnimationUtils.loadAnimation(context, R.anim.translate_anim);
mainLayout.setAnimation(translate_anim);
}
}
}
And the full code for my MainActivity:
package com.benjamin.kwok.recipertracker;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.core.app.ActivityCompat;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.Manifest;
import android.app.Activity;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
FloatingActionButton add_button;
FloatingActionButton camera_button;
ImageView empty_imageview;
ImageView imageView;
TextView no_data;
MyDatabaseHelper myDB;
ArrayList<String> recipe_id, recipe_title, recipe_description, recipe_minutes;
CustomAdapter customAdapter;
final static private int NEW_PICTURE = 1;
private String mCameraFileName;
private static final String TAG = "CapturePicture";
static final int REQUEST_PICTURE_CAPTURE = 1;
private String pictureFilePath;
private String deviceIdentifier;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},1);
// SharedPreferences mSharedPreference= PreferenceManager.getDefaultSharedPreferences(this);
// SharedPreferences.Editor editor = mSharedPreference.edit();
// String text= mSharedPreference.getString(getString(R.string.name), "");
//// name_output.setText(text);
recyclerView = findViewById(R.id.recyclerView);
add_button = findViewById(R.id.add_button);
camera_button = findViewById(R.id.camera_button);
empty_imageview = findViewById(R.id.empty_imageview);
imageView = findViewById(R.id.imageView);
no_data = findViewById(R.id.no_data);
add_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, AddActivity.class);
startActivity(intent);
}
});
camera_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 100);
}
});
myDB = new MyDatabaseHelper(MainActivity.this);
recipe_id = new ArrayList<>();
recipe_title = new ArrayList<>(10);
recipe_description = new ArrayList<>();
recipe_minutes = new ArrayList<>();
storeDataInArrays();
customAdapter = new CustomAdapter(MainActivity.this,this, recipe_id, recipe_title, recipe_description,
recipe_minutes);
recyclerView.setAdapter(customAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
loadData();
}
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100) {
Bundle bundle = data.getExtras();
Bitmap captureImage = (Bitmap) bundle.get("data");
imageView.setImageBitmap(captureImage);
saveToGallery();
}
if(resultCode == RESULT_OK){
Toast.makeText(this, "Image added to Gallery", Toast.LENGTH_LONG);
}
}
private void saveToGallery(){
BitmapDrawable draw = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = draw.getBitmap();
FileOutputStream outStream = null;
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath() + "/RecipeImages");
dir.mkdirs();
String fileName = String.format("%d.jpg", System.currentTimeMillis());
File outFile = new File(dir, fileName);
MediaScannerConnection.scanFile(this, new String[] { outFile.getPath() }, new String[] { "image/jpeg" }, null);
try {
outStream = new FileOutputStream(outFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
try {
outStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
void storeDataInArrays(){
Cursor cursor = myDB.readAllData();
if(cursor.getCount() == 0){
empty_imageview.setVisibility(View.VISIBLE);
no_data.setVisibility(View.VISIBLE);
}else{
while (cursor.moveToNext()){
recipe_id.add(cursor.getString(0));
recipe_title.add(cursor.getString(1));
recipe_description.add(cursor.getString(2));
recipe_minutes.add(cursor.getString(3));
}
empty_imageview.setVisibility(View.GONE);
no_data.setVisibility(View.GONE);
}
}
public void loadData() {
SharedPreferences mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String name = mPreferences.getString("name","");
setTitle(name+"'s" + " Recipe Tracker");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.my_menu, menu);
// return super.onCreateOptionsMenu(menu);
MenuItem searchItem = menu.findItem(R.id.actionSearch);
// getting search view of our item.
SearchView searchView = (SearchView) searchItem.getActionView();
// below line is to call set on query text listener method.
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
// inside on query text change method we are
// calling a method to filter our recycler view.
filter(newText);
return false;
}
});
return true;
}
private void filter(String text) {
// creating a new array list to filter our data.
ArrayList filteredlist = new ArrayList<>();
// running a for loop to compare elements.
for (String item : recipe_title) {
// checking if the entered string matched with any item of our recycler view.
if (item.toLowerCase().contains(text.toLowerCase())) {
// if the item is matched we are
// adding it to our filtered list.
filteredlist.add(item);
}
}
if (filteredlist.isEmpty()) {
// if no item is added in filtered list we are
// displaying a toast message as no data found.
Toast.makeText(this, "No Data Found..", Toast.LENGTH_SHORT).show();
} else {
// at last we are passing that filtered
// list to our adapter class.
customAdapter.filterList(filteredlist);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.delete_all){
confirmDialog();
}
return super.onOptionsItemSelected(item);
}
void confirmDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Delete All?");
builder.setMessage("Are you sure you want to delete all Data?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
MyDatabaseHelper myDB = new MyDatabaseHelper(MainActivity.this);
myDB.deleteAllData();
//Refresh Activity
Intent intent = new Intent(MainActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.create().show();
}
}
As soon as I start typing in a new search query, this error seems to get thrown.

Use onActivityResult in RecyclerViewAdapter

I am trying to use onActivityResult in my RecyclerViewAdapter. But I get the error that the 'The method does not override from its superclass'. I tried implementing the interface but onActivityResult never gets called. I have already searched enough on the StackOverflow questions like this one but couldn't find anything helpful.
RecyclerViewAdapter.java
package com.example.waheed.telegramchat;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.RecyclerViewHolder> {
//String arrays to store user data
static String[] contact_name, Phone_no, user_id;
Context context;
public RecyclerAdapter(String[] contact_name, String[] Phone_no, String[] user_id, Context context) {
//Getting the data from MainActivity.java
this.context = context;
this.user_id = user_id;
this.contact_name = contact_name;
this.Phone_no = Phone_no;
}
#NonNull
#Override
public RecyclerAdapter.RecyclerViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
//Setting the row layout for Recyclerview
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_layout, parent, false);
RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(view, this.context);
return recyclerViewHolder;
}
#Override
public void onBindViewHolder(#NonNull RecyclerViewHolder holder, int position) {
holder.tx_contact.setText(contact_name[position]);
holder.tx_phone.setText(Phone_no[position]);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getItemCount() {
return contact_name.length;
}
public static class RecyclerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
Context context;
TextView tx_contact, tx_phone;
ImageButton message_btn;
static ImageView img_profile;
public RecyclerViewHolder(View itemView, Context context) {
super(itemView);
tx_contact = (TextView) itemView.findViewById(R.id.txt_contactname);
tx_phone = (TextView) itemView.findViewById(R.id.phonenumber);
message_btn = (ImageButton) itemView.findViewById(R.id.chat_icon);
img_profile = (ImageView) itemView.findViewById(R.id.profile_pic);
this.context = context;
//Calling onclick function
message_btn.setOnClickListener(this);
img_profile.setOnClickListener(this);
}
public void makeCall(String ID, String name, String packageName, String className) {
//
String data = "content://com.android.contacts/data/" + ID;
// Build the intent
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
// the _ids you save goes here at the end of /data/id
intent.setData(Uri.parse("content://com.android.contacts/data/" + ID));
intent.setDataAndType(Uri.parse(data), className);
intent.setPackage(packageName);
// Verify it resolves
PackageManager packageManager = context.getPackageManager();
List<ResolveInfo> activities = packageManager.queryIntentActivities(intent, 0);
boolean isIntentSafe = activities.size() > 0;
Log.d("See this " + ID, activities.size() + "");
// Start an activity if it's safe
if (isIntentSafe) {
try {
//Toast to show which user is being called
context.startActivity(intent);
Toast.makeText(context, "Opening chat with " + name + " on Telegram", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(context, "OOPS!,Something went wrong\nPlease grant app permissions in setting or send feedback.", Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onClick(View v) {
//Getting the position of the item clicked
int i = getAdapterPosition();
//Storing the selected items in Strings
String name = RecyclerAdapter.contact_name[i];
String phone = RecyclerAdapter.Phone_no[i];
String ID = RecyclerAdapter.user_id[i];
String mimeType = "vnd.android.cursor.item/vnd.org.telegram.messenger.android.profile";
String packageName = "org.telegram.messenger";
switch (v.getId()) {
case R.id.chat_icon:
makeCall(ID, name, packageName, mimeType);
break;
case R.id.profile_pic:
Intent intent = new Intent(this.context, showImages.class);
((Activity) context).startActivityForResult(intent, 1);
break;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Bitmap bitmap;
if (requestCode == 1) {
if (resultCode == showImages.RESULT_OK) {
String result = data.getStringExtra("result");
Toast.makeText(this.context, "Clicked item is " + result, Toast.LENGTH_SHORT).show();
bitmap = BitmapFactory.decodeFile(result);
RecyclerViewHolder.img_profile.setImageBitmap(bitmap);
}
if (resultCode == showImages.RESULT_CANCELED) {
//Write your code if there's no result
}
}
}
}
}
showImages.java
package com.example.waheed.telegramchat;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import com.ImageAdapter;
import java.io.File;
import java.util.ArrayList;
public class showImages extends AppCompatActivity {
ImageAdapter myImageAdapter;
GridView gridView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_images);
gridView = (GridView) findViewById(R.id.gridview);
myImageAdapter = new ImageAdapter(this);
gridView.setAdapter(myImageAdapter);
String ExternalStorageDirectoryPath = Environment
.getExternalStorageDirectory()
.getAbsolutePath();
String targetPath = ExternalStorageDirectoryPath + "/Android/data/org.telegram.messenger/cache/";
File targetDirector = new File(targetPath);
final ArrayList<String> imagePaths = new ArrayList<String>();
final File[] files = targetDirector.listFiles();
for (File file : files) {
if (file.getName().toLowerCase().endsWith(".jpg") ||
file.getName().toLowerCase().endsWith(".png")) {
imagePaths.add(file.getAbsolutePath());
myImageAdapter.add(file.getAbsolutePath());
}
}
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String result = imagePaths.get(position);
Intent returnIntent = new Intent();
returnIntent.putExtra("result", result);
setResult(showImages.RESULT_OK, returnIntent);
finish();
}
});
}
}
The RecyclerView.ViewHolder class does not contain a definition of an onActivityResult method that it can override.
onActivityResult, as far as I understand, only appears as a method of the Activity & Fragment classes.
Move the code
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Bitmap bitmap;
if (requestCode == 1) {
if (resultCode == showImages.RESULT_OK) {
String result = data.getStringExtra("result");
Toast.makeText(this.context, "Clicked item is " + result, Toast.LENGTH_SHORT).show();
bitmap = BitmapFactory.decodeFile(result);
RecyclerViewHolder.img_profile.setImageBitmap(bitmap);
}
if (resultCode == showImages.RESULT_CANCELED) {
//Write your code if there's no result
}
}
}
to the class that initiated the call to showImages. I noticed that showImages closes when item is clicked.
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String result = imagePaths.get(position);
Intent returnIntent = new Intent();
returnIntent.putExtra("result", result);
setResult(showImages.RESULT_OK, returnIntent);
finish();
}
});
You have to override onActivityResult in your activity wich contains the recyclerview not in viewholder class
You must implement onActivityResult in your activity class not in RecyclerViewAdapter. This method is used from your activity to retrieve data from other intents/activities that have started from your activity and normally
it has no place inside RecyclerViewAdapter.
you should use onActivityForResult in activity ,and create interface to handle action ,logic - adapter only display view.

favorite Recycler view updates only on relaunching app

I developed a word app that contains English vocabularies and users can add their favorite word by clicking on a floating button. Every time my favorite list has at list one item it is updated but when it's empty it doesn't show anything but when I run app again list updates.
if you need any code let me know to send it .
UPDATE:
Inner page :
selectDb();
if(selectFavoriteState()){
favorite.setImageResource(R.drawable.ic_favorite_like);
}else {
favorite.setImageResource(R.drawable.ic_favorite_maylike);
}
favorite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (selectFavoriteState()){
favorite.setImageResource(R.drawable.ic_favorite_maylike);
updateUnfavorited();
}else {
favorite.setImageResource(R.drawable.ic_favorite_like);
updateFavorited();
}
}
});
private void selectDb(){
destpath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/ielts/";
database = SQLiteDatabase.openOrCreateDatabase(destpath + "/md_book.db", null);
}
private boolean selectFavoriteState(){
#SuppressLint("Recycle") Cursor cursor = database.rawQuery("SELECT * FROM main WHERE id = " + id, null);
while (cursor.moveToNext()){
favoriteState = cursor.getString(cursor.getColumnIndex("fav"));
}
return favoriteState.equals("1");
}
private void updateFavorited(){
database.execSQL( "UPDATE main SET fav = 1 WHERE id = " + id);
}
private void updateUnfavorited(){
database.execSQL( "UPDATE main SET fav = 0 WHERE id = " + id);
}
Update 2:
package farmani.com.essentialwordsforielts.mainPage;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import farmani.com.essentialwordsforielts.R;
public class PageFragment extends Fragment {
private int mPage;
public static final String ARG_PAGE = "ARG_PAGE";
RecyclerView recyclerView;
AdapterFav adapterFav;
public static PageFragment newInstance(int page) {
Bundle args = new Bundle();
args.putInt(ARG_PAGE, page);
PageFragment fragment = new PageFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate( Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPage = getArguments().getInt(ARG_PAGE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_page, container, false);
if (mPage == 1) {
recyclerView = (RecyclerView) view.findViewById(R.id.my_recycler_view);
AdapterList adapter = new AdapterList(MainActivity.context);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.context));
}
if (mPage == 2) {
recyclerView = (RecyclerView) view.findViewById(R.id.my_recycler_view);
adapterFav = new AdapterFav(MainActivity.context);
recyclerView.setAdapter(adapterFav);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.context));
}
return view;
}
#Override
public void onResume() {
super.onResume();
if (adapterFav != null){
adapterFav.notifyDataSetChanged();
}
}
}
Update 3 :AdapterFav
package farmani.com.essentialwordsforielts.mainPage;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import farmani.com.essentialwordsforielts.R;
import farmani.com.essentialwordsforielts.innerpage.ActivityInnerPage;
public class AdapterFav extends RecyclerView.Adapter<ViewHolder> {
Context context;
LayoutInflater inflater;
TextView title;
ImageView avatar;
LinearLayout cardAdapter;
public AdapterFav(Context context){
this.context = context;
inflater = LayoutInflater.from(context);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.adapter_card_view, parent, false);
title = (TextView) view.findViewById(R.id.title1);
avatar = (ImageView) view.findViewById(R.id.avatar);
cardAdapter = (LinearLayout) view.findViewById(R.id.card_adapter);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.title.setText(MainActivity.favorite.get(position).getWord());
String img = MainActivity.favorite.get(position).getImg();
int id = MainActivity.context.getResources().getIdentifier(img, "drawable", MainActivity.context.getPackageName());
holder.avatar.setImageResource(id);
holder.cardAdapter.setOnClickListener(clickListener);
holder.cardAdapter.setId(position);
}
View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = view.getId();
Intent intent = new Intent (MainActivity.context, ActivityInnerPage.class);
intent.putExtra("name", "favorite");
intent.putExtra("id", position + "");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MainActivity.context.startActivity(intent);
}
};
#Override
public int getItemCount() {
return MainActivity.favorite.size();
}
}
Update 4: MainActivity
package farmani.com.essentialwordsforielts.mainPage;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import com.nabinbhandari.android.permissions.PermissionHandler;
import com.nabinbhandari.android.permissions.Permissions;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import farmani.com.essentialwordsforielts.R;
import farmani.com.essentialwordsforielts.search.ActivitySearch;
import farmani.com.essentialwordsforielts.setting.ActivitySetting;
public class MainActivity extends AppCompatActivity {
public static Context context;
public static ArrayList<Structure> list = new ArrayList<>();
public static ArrayList<Structure> favorite = new ArrayList<>();
DrawerLayout drawerLayout;
NavigationView navigationView;
ImageView hamburger;
SQLiteDatabase database;
String destPath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navigation_activity_main);
Permissions.check(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE},
" storage permissions are required to copy database", new Permissions.Options()
.setSettingsDialogTitle("Warning!").setRationaleDialogTitle("Info"),
new PermissionHandler() {
#Override
public void onGranted() {
setupDB();
selectList();
selectFavorite();
}
});
context = getApplicationContext();
setTabOption();
drawerLayout = findViewById(R.id.navigation_drawer);
navigationView = findViewById(R.id.navigation_view);
hamburger = findViewById(R.id.hamburger);
hamburger.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
drawerLayout.openDrawer(Gravity.START);
}
});
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.exit) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
MainActivity.this);
alertDialog.setTitle(R.string.exit);
alertDialog.setMessage(R.string.exit_ask);
alertDialog.setCancelable(false);
alertDialog.setPositiveButton(R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int
which) {
finish();
}
});
alertDialog.setNegativeButton(R.string.no,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int
which) {
dialog.cancel();
}
});
alertDialog.show();
}else if (id == R.id.search) {
Intent intent = new Intent(MainActivity.this, ActivitySearch.class);
MainActivity.this.startActivity(intent);
} else if (id == R.id.setting) {
Intent intent = new Intent(MainActivity.this, ActivitySetting.class);
MainActivity.this.startActivity(intent);
}
return true;
}
});
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(Gravity.START)) {
drawerLayout.closeDrawer(Gravity.START);
} else {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
MainActivity.this);
alertDialog.setTitle(R.string.exit);
alertDialog.setMessage(R.string.exit_ask);
alertDialog.setCancelable(false);
alertDialog.setPositiveButton(R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertDialog.setNegativeButton(R.string.no,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
}
private void setTabOption() {
ViewPager viewPager = findViewById(R.id.viewpager);
viewPager.setAdapter(new AdapterFragment(getSupportFragmentManager(),
context));
TabLayout tabStrip = findViewById(R.id.tabs);
tabStrip.setupWithViewPager(viewPager);
}
#Override
protected void onResume() {
super.onResume();
if (!list.isEmpty()){
list.clear();
selectList();
} if (!favorite.isEmpty()){
favorite.clear();
selectFavorite();
}
}
private void setupDB() {
try {
destPath =
Environment.getExternalStorageDirectory().getAbsolutePath() + "/ielts/";
File file = new File(destPath);
if (!file.exists()) {
file.mkdirs();
file.createNewFile();
CopyDB(getBaseContext().getAssets().open("md_book.db"),
new FileOutputStream(destPath + "/md_book.db"));
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
private void CopyDB(InputStream inputStream, OutputStream outputStream)
throws IOException {
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
}
private void selectFavorite() {
database = SQLiteDatabase.openOrCreateDatabase(destPath + "/md_book.db",
null);
#SuppressLint("Recycle") Cursor cursor = database.rawQuery("SELECT * FROM main WHERE fav = 1",
null);
while (cursor.moveToNext()) {
String word = cursor.getString(cursor.getColumnIndex("word"));
String definition =
cursor.getString(cursor.getColumnIndex("definition"));
String trans = cursor.getString(cursor.getColumnIndex("trans"));
String img = cursor.getString(cursor.getColumnIndex("img"));
int id = cursor.getInt(cursor.getColumnIndex("id"));
Structure struct = new Structure(word, definition, trans, img, id);
struct.setWord(word);
struct.setDefinition(definition);
struct.setTrans(trans);
struct.setImg(img);
struct.setId(id);
favorite.add(struct);
}
}
private void selectList() {
database = SQLiteDatabase.openOrCreateDatabase(destPath + "/md_book.db",
null);
#SuppressLint("Recycle") Cursor cursor = database.rawQuery("SELECT * FROM main", null);
while (cursor.moveToNext()) {
String word = cursor.getString(cursor.getColumnIndex("word"));
String definition =
cursor.getString(cursor.getColumnIndex("definition"));
String trans = cursor.getString(cursor.getColumnIndex("trans"));
String img = cursor.getString(cursor.getColumnIndex("img"));
int id = cursor.getInt(cursor.getColumnIndex("id"));
Structure struct = new Structure(word, definition, trans, img, id);
struct.setWord(word);
struct.setDefinition(definition);
struct.setTrans(trans);
struct.setImg(img);
struct.setId(id);
list.add(struct);
}
}
}
Update 5 innerpage activity
package farmani.com.essentialwordsforielts.innerpage;
import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toolbar;
import java.lang.reflect.Field;
import farmani.com.essentialwordsforielts.R;
import farmani.com.essentialwordsforielts.mainPage.AdapterFav;
public class ActivityInnerPage extends AppCompatActivity {
private TextView contentDescriptione;
private TextView moreDescriptione;
private ImageView avatar;
private ImageView imgCopy;
private ImageView imgShare;
private ImageView imgSms;
private ImageView imgGmail;
private FloatingActionButton favorite;
private CollapsingToolbarLayout collapsingToolbarLayout;
public String word;
public String definition;
public String trans;
public String img;
public int id;
private String destpath;
private SQLiteDatabase database;
private String favoriteState;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inner_page);
final android.support.v7.widget.Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(),MainActivity.class);
startActivity(i);
finish();
}
});
Bundle extras = getIntent().getExtras();
if (extras != null) {
int layoutId = Integer.parseInt(extras.getString("id"));
String pageName = extras.getString("name");
assert pageName != null;
if (pageName.equals("list")) {
id = MainActivity.list.get(layoutId).getId();
word = MainActivity.list.get(layoutId).getWord();
definition = MainActivity.list.get(layoutId).getDefinition();
trans = MainActivity.list.get(layoutId).getTrans();
img = MainActivity.list.get(layoutId).getImg();
} else if (pageName.equals("favorite")) {
id = MainActivity.favorite.get(layoutId).getId();
word = MainActivity.favorite.get(layoutId).getWord();
definition = MainActivity.favorite.get(layoutId).getDefinition();
trans = MainActivity.favorite.get(layoutId).getTrans();
img = MainActivity.favorite.get(layoutId).getImg();
}
}
contentDescriptione = findViewById(R.id.content_description);
moreDescriptione = findViewById(R.id.more_description);
imgCopy = findViewById(R.id.img_copy);
imgShare = findViewById(R.id.img_share);
imgSms = findViewById(R.id.img_sms);
imgGmail = findViewById(R.id.img_gmail);
avatar = findViewById(R.id.avatar);
favorite = findViewById(R.id.favorite);
collapsingToolbarLayout = findViewById(R.id.collapsing_toolbar);
collapsingToolbarLayout.getExpandedTitleMarginStart();
collapsingToolbarLayout.setTitle(word);
collapsingToolbarLayout.setExpandedTitleColor(getResources().getColor(android.R.color.holo_red_light));
contentDescriptione.setText(definition);
moreDescriptione.setText(trans);
int imgageId = MainActivity.context.getResources().getIdentifier(img, "drawable", MainActivity.context.getPackageName());
avatar.setImageResource(imgageId);
SharedPreferences prefes = getSharedPreferences("font_size", MODE_PRIVATE);
int value = prefes.getInt("fontsize", 16);
contentDescriptione.setTextSize(value);
moreDescriptione.setTextSize(value);
selectDb();
if(selectFavoriteState()){
favorite.setImageResource(R.drawable.ic_favorite_like);
}else {
favorite.setImageResource(R.drawable.ic_favorite_maylike);
}
favorite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (selectFavoriteState()){
favorite.setImageResource(R.drawable.ic_favorite_maylike);
updateUnfavorited();
}else {
favorite.setImageResource(R.drawable.ic_favorite_like);
updateFavorited();
}
}
});
imgCopy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final ClipboardManager clipboardManager =
(ClipboardManager)ActivityInnerPage.this.getSystemService(Context.CLIPBOARD_SERVICE);
final ClipData clip = ClipData.newPlainText(word, trans+definition);
assert clipboardManager != null;
clipboardManager.setPrimaryClip(clip);
Snackbar.make(view,"متن کپی شد ",Snackbar.LENGTH_SHORT).show();
}
});
imgShare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, definition+trans);
shareIntent.putExtra(Intent.EXTRA_SUBJECT, word);
startActivity(Intent.createChooser(shareIntent, "Share"));
}
});
imgGmail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
Intent emailIntent = new Intent(Intent.ACTION_SENDTO
, Uri.fromParts("mailto", "", null));
emailIntent.putExtra(Intent.EXTRA_SUBJECT, word);
emailIntent.putExtra(Intent.EXTRA_TEXT, definition);
startActivity(Intent.createChooser(emailIntent, "Send email..."));
}catch (Exception e){
Snackbar.make(view,"برنامه ای برای ارسال ایمیل یافت نشد",Snackbar.LENGTH_SHORT).show();
}
}
});
imgSms.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
Intent sendSms = new Intent(Intent.ACTION_VIEW);
sendSms.putExtra("sms_body", definition + trans);
sendSms.setType("vnd.android-dir/mms-sms");
startActivity(sendSms);
}catch (Exception e){
Snackbar.make(view,"برنامه ای برای ارسال پیام یافت نشد",Snackbar.LENGTH_SHORT).show();
}
}
});
}
private void selectDb(){
destpath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/ielts/";
database = SQLiteDatabase.openOrCreateDatabase(destpath + "/md_book.db", null);
}
private boolean selectFavoriteState(){
#SuppressLint("Recycle") Cursor cursor = database.rawQuery("SELECT * FROM main WHERE id = " + id, null);
while (cursor.moveToNext()){
favoriteState = cursor.getString(cursor.getColumnIndex("fav"));
}
return favoriteState.equals("1");
}
private void updateFavorited(){
database.execSQL( "UPDATE main SET fav = 1 WHERE id = " + id);
}
private void updateUnfavorited(){
database.execSQL( "UPDATE main SET fav = 0 WHERE id = " + id);
}
}
In your FloatingActionButton onClick method after you save the new item in your database, insert your new item into your recyclerview datasource list and call notifyDatasetChanged() on the adapter.
Choice 1: in onResume() stub of MainActivity, call selectList() and selectFavorite() and then load the PageFragment again so that the new list is loaded properly.
This is the shortest wayout but this approach is very much unoptimized and is not recommended.
Choice 2: You will have to insert the new item in database as well as add it to the List and then call notifyDatasetChanged
In MainActivity within methods selectList() and selectFavorite() after you perform list.add(struct) and favourite.add(struct) respectively, you will have to call notifyDatasetChanged() for the Adapter.
But the problem is your RecyclerView is in the PageFragment whereas you're populating the list in MainActivity.
So move your selectList() and selectFavorite() to PageFragment where you first initialize the RecylerView then, set the Adapter and then populate the list and finally call notifyDatasetChanged() on your adapters.

Failed Binder Transaction is Ruining Entire Widget

In my widget, I am constantly getting this error:
11-02 09:35:10.613: D/D&D(1557): onCreate called
11-02 09:35:10.933: E/JavaBinder(1557): !!! FAILED BINDER TRANSACTION !!!
11-02 09:35:10.933: D/AppInfoAdapter(1557): top
No matter what I seem to do (I've tried cutting down bitmap sizes, making bitmaps static, commenting out parts of my coding to see where the error was (which didn't help at all by the way)), I always get this error. What this error is causing is that it makes my listView of the users installed applications not show up at all (it's just white space) in a sliding drawer. All my links and other classes work just fine. (But my listView is the center piece and major function of my entire widget.)
I'm at a loss now so I am just going to post the three suspected classes that I've concluded this is steming from (because all the other classes work fine).
Please note that some code is commented out (such as coding for drag and drop functionality because my real device doesn't support honeycomb. I will implement that code when my listView starts working again however)
AppInfoAdapter.java:
package com.example.awesomefilebuilderwidget;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
public class AppInfoAdapter extends BaseAdapter implements Filterable {
private Context mContext;
private List<PackageInfo> mListAppInfo;
private PackageManager mPackManager;
private List<PackageInfo> originalListAppInfo;
private Filter filter;
public AppInfoAdapter(Context c, List<PackageInfo> listApp,
PackageManager pm) {
mContext = c;
this.originalListAppInfo = this.mListAppInfo = listApp;
mPackManager = pm;
Log.d("AppInfoAdapter", "top");
}
#Override
public int getCount() {
Log.d("AppInfoAdapter", "getCount()");
return mListAppInfo.size();
}
#Override
public Object getItem(int position) {
Log.d("AppInfoAdapter", "getItem");
return mListAppInfo.get(position);
}
#Override
public long getItemId(int position) {
Log.d("AppInfoAdapter", "getItemId");
return position;
}
public static Bitmap scaleDownBitmap(Bitmap default_b, int newHeight, Context c) {
final float densityMultiplier = c.getResources().getDisplayMetrics().density;
int h= (int) (100*densityMultiplier);
int w= (int) (h * default_b.getWidth()/((double) default_b.getHeight()));
default_b=Bitmap.createScaledBitmap(default_b, w, h, true);
// TO SOLVE LOOK AT HERE:https://stackoverflow.com/questions/15517176/passing-bitmap-to-other-activity-getting-message-on-logcat-failed-binder-transac
return default_b;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// get the selected entry
final PackageInfo entry = (PackageInfo) mListAppInfo.get(position);
// reference to convertView
View v = convertView;
// inflate new layout if null
if (v == null) {
LayoutInflater inflater = LayoutInflater.from(mContext);
v = inflater.inflate(R.layout.layout_appinfo, null);
Log.d("AppInfoAdapter", "New layout inflated");
}
// load controls from layout resources
ImageView ivAppIcon = (ImageView) v.findViewById(R.id.ivIcon);
TextView tvAppName = (TextView) v.findViewById(R.id.tvName);
TextView tvPkgName = (TextView) v.findViewById(R.id.tvPack);
final CheckBox addCheckbox = (CheckBox) v
.findViewById(R.id.addCheckbox);
Log.d("AppInfoAdapter", "Controls from layout Resources Loaded");
// set data to display
ivAppIcon.setImageDrawable(entry.applicationInfo.loadIcon(mPackManager));
tvAppName.setText(entry.applicationInfo.loadLabel(mPackManager));
tvPkgName.setText(entry.packageName);
Log.d("AppInfoAdapter", "Data Set To Display");
addCheckbox
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (addCheckbox.isChecked()) {
System.out.println("Checked");
PackageManager pm = mContext.getPackageManager();
Drawable icon = null;
try {
icon = pm
.getApplicationIcon(entry.packageName);
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Drawable default_icon = pm.getDefaultActivityIcon();
if (icon instanceof BitmapDrawable
&& default_icon instanceof BitmapDrawable) {
BitmapDrawable icon_bd = (BitmapDrawable) icon;
Bitmap icon_b = icon_bd.getBitmap();
BitmapDrawable default_bd = (BitmapDrawable) pm
.getDefaultActivityIcon();
Bitmap default_b = default_bd.getBitmap();
if (icon_b == default_b) {
// It's the default icon
scaleDownBitmap(default_b, 100, v.getContext());
Log.d("AppInfoAdapter", "Scale Bitmap Chosen");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
default_b.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
Log.d("AppInfoAdapter", "Scale Bitmap to Array");
Intent intent = new Intent(v.getContext(), GridView.class);
intent.putExtra("picture", byteArray);
v.getContext().startActivity(intent);
Log.d("AppInfoAdapter", "Intent started to send Bitmap");
}
}
} else {
System.out.println("Un-Checked");
}
}
});
// return view
return v;
}
#Override
public Filter getFilter() {
if (filter == null) {
filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
List<PackageInfo> myFilteredAppList = new ArrayList<PackageInfo>();
constraint = constraint.toString().toLowerCase();
if (constraint.length() == 0) {
myFilteredAppList.addAll(originalListAppInfo);
}
for (PackageInfo appInfo : originalListAppInfo) {
String somefield = appInfo.packageName;
String name = appInfo.packageName;
if (somefield.toLowerCase().contains(
constraint.toString().toLowerCase().toString())
|| (name != null && name.toLowerCase()
.contains(
constraint.toString()
.toLowerCase()
.toString()))) {
myFilteredAppList.add(appInfo);
}
}
results.count = myFilteredAppList.size();
results.values = myFilteredAppList;
return results;
}
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
if (results.values != null) {
mListAppInfo = (List<PackageInfo>) results.values;
notifyDataSetChanged();
}
}
};
}
return filter;
}
}
Drag_and_Drop_App (snippet):
public class Drag_and_Drop_App extends Activity {
private static final int SET_BACKGROUND = 10;
private ListView mListAppInfo;
// Search EditText
EditText inputSearch;
public AppInfoAdapter adapter;
final SwipeDetector swipeDetector = new SwipeDetector();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set layout for the main screen
setContentView(R.layout.drag_and_drop_app);
// import buttons
Button btnLinkToPersonalize = (Button) findViewById(R.id.btnLinkToPersonalize);
Log.d("D&D", "onCreate called");
// create new adapter
adapter = new AppInfoAdapter(this, (List<PackageInfo>) Utilities.getInstalledApplications(this), getPackageManager());
// load list application
mListAppInfo = (ListView)findViewById(R.id.lvApps);
// set adapter to list view
mListAppInfo.setAdapter(adapter);
// search bar
inputSearch = (EditText) findViewById(R.id.inputSearch);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
// Drag_and_Drop_App.this.adapter.getFilter().filter(cs);
if (Drag_and_Drop_App.this.adapter == null){
// some print statement saying it is null
Log.d ("msg_error", "adapter_is_null");
}
Drag_and_Drop_App.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
// implement event when an item on list view is selected
mListAppInfo.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
// get the list adapter
AppInfoAdapter appInfoAdapter = (AppInfoAdapter)parent.getAdapter();
// get selected item on the list
PackageInfo appInfo = (PackageInfo)appInfoAdapter.getItem(pos);
// launch the selected application
Utilities.launchApp(parent.getContext(), getPackageManager(), appInfo.packageName);
}
});
// implement event when an item on list view is selected via long-click
mListAppInfo.setOnItemLongClickListener(new OnItemLongClickListener(){
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,int pos, long id) {
if (swipeDetector.swipeDetected()){
// do the onSwipe action
} else {
// do the onItemLongClick action
// get the list adapter
AppInfoAdapter appInfoAdapter = (AppInfoAdapter)parent.getAdapter();
// get selected item on the list
PackageInfo appInfo = (PackageInfo)appInfoAdapter.getItem(pos);
// launch the selected application
Utilities.launchApp(parent.getContext(), getPackageManager(), appInfo.packageName);
Log.d("D&D", "App launched");
}
return true;
}
});
// implement slide event to open up plus button
mListAppInfo.setOnTouchListener(swipeDetector);
mListAppInfo.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
if (swipeDetector.swipeDetected()){
// do the onSwipe action
// TEST TO MAKE SURE SWIPE WORKS
AppInfoAdapter appInfoAdapter = (AppInfoAdapter)parent.getAdapter();
// get selected item on the list
PackageInfo appInfo = (PackageInfo)appInfoAdapter.getItem(pos);
// launch the selected application
Utilities.launchApp(parent.getContext(), getPackageManager(), appInfo.packageName);
} else {
// do the onItemClick action
// get the list adapter
AppInfoAdapter appInfoAdapter = (AppInfoAdapter)parent.getAdapter();
// get selected item on the list
PackageInfo appInfo = (PackageInfo)appInfoAdapter.getItem(pos);
// launch the selected application
Utilities.launchApp(parent.getContext(), getPackageManager(), appInfo.packageName);
}
}
});
And finally GridView.java:
package com.example.awesomefilebuilderwidget;
import java.util.ArrayList;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipDescription;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.DragEvent;
import android.view.View;
import android.view.View.OnDragListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
public class GridView extends Activity { // implements OnItemLongClickListener, OnDragListener{
ArrayList<Integer> drawables = new ArrayList<Integer>();
private BaseAdapter adapter;
private int draggedIndex = -1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drag_and_drop_app);
Log.d("GridView", "onCreate called");
drawables = new ArrayList<Integer>();
drawables.add(R.drawable.pattern1);
drawables.add(R.drawable.pattern2);
android.widget.GridView gridView = (android.widget.GridView) findViewById(R.id.grid_view);
// gridView.setOnItemLongClickListener(this);
gridView.setAdapter(adapter = new BaseAdapter() {
#Override
// Get a View that displays the data at the specified position in
// the data set.
public View getView(int position, View convertView,
ViewGroup gridView) {
// try to reuse the views.
ImageView view = (ImageView) convertView;
// if convert view is null then create a new instance else reuse
// it
if (view == null) {
view = new ImageView(GridView.this);
}
Bundle extras = getIntent().getExtras();
byte[] byteArray = extras.getByteArray("picture");
Bitmap default_b = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
view.setImageBitmap(default_b);
view.setImageResource(drawables.get(position));
view.setScaleType(ImageView.ScaleType.CENTER_CROP);
view.setLayoutParams(new android.widget.GridView.LayoutParams(70, 70));
view.setTag(String.valueOf(position));
return view;
}
#Override
// Get the row id associated with the specified position in the
// list.
public long getItemId(int position) {
return position;
}
#Override
// Get the data item associated with the specified position in the
// data set.
public Object getItem(int position) {
return drawables.get(position);
}
#Override
// How many items are in the data set represented by this Adapter.
public int getCount() {
return drawables.size();
}
});
}
/*#Override
public boolean onItemLongClick(AdapterView<?> gridView, View view,
int position, long row) {
ClipData.Item item = new ClipData.Item((String) view.getTag());
ClipData clipData = new ClipData((CharSequence) view.getTag(),
new String[] { ClipDescription.MIMETYPE_TEXT_PLAIN }, item);
view.startDrag(clipData, new View.DragShadowBuilder(view), null, 0);
View trashCan = findViewById(R.id.trash_can);
trashCan.setVisibility(View.VISIBLE);
trashCan.setOnDragListener(GridView.this);
trashCan.setOnDragListener(GridView.this);
draggedIndex = position;
return true;
}
#Override
public boolean onDrag(View view, DragEvent dragEvent) {
switch (dragEvent.getAction()) {
case DragEvent.ACTION_DRAG_STARTED:
// Drag has started
// If called for trash resize the view and return true
if (view.getId() == R.id.trash_can) {
view.animate().scaleX(1.0f);
view.animate().scaleY(1.0f);
return true;
} else // else check the mime type and set the view visibility
if (dragEvent.getClipDescription().hasMimeType(
ClipDescription.MIMETYPE_TEXT_PLAIN)) {
view.setVisibility(View.GONE);
return true;
} else {
return false;
}
case DragEvent.ACTION_DRAG_ENTERED:
// Drag has entered view bounds
// If called for trash can then scale it.
if (view.getId() == R.id.trash_can) {
view.animate().scaleX(1.5f);
view.animate().scaleY(1.5f);
}
return true;
case DragEvent.ACTION_DRAG_EXITED:
// Drag exited view bounds
// If called for trash can then reset it.
if (view.getId() == R.id.trash_can) {
view.animate().scaleX(1.0f);
view.animate().scaleY(1.0f);
}
view.invalidate();
return true;
case DragEvent.ACTION_DRAG_LOCATION:
// Ignore this event
return true;
case DragEvent.ACTION_DROP:
// Dropped inside view bounds
// If called for trash can then delete the item and reload the grid
// view
if (view.getId() == R.id.trash_can) {
drawables.remove(draggedIndex);
draggedIndex = -1;
}
adapter.notifyDataSetChanged();
case DragEvent.ACTION_DRAG_ENDED:
// Hide the trash can
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
findViewById(R.id.trash_can).setVisibility(View.GONE);
}
}, 1000l);
if (view.getId() == R.id.trash_can) {
view.animate().scaleX(1.0f);
view.animate().scaleY(1.0f);
} else {
view.setVisibility(View.VISIBLE);
}
// remove drag listeners
view.setOnDragListener(null);
return true;
}
return false;
}*/
}
Please comment if you notice ANYTHING that doesn't seem right or that is wrong. I have been trying to fix this error for days and have tried the stackoverflow links here, here, here, and others on top of those.
Please help me to fix this error that I keep getting. I'm really at a loss at what to do now...
(Thanks for reading all of this too, I know it was a lot)
Here is my Utilities class:
package com.example.awesomefilebuilderwidget;
import java.util.List;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
public class Utilities {
/*
* Get all installed application on mobile and return a list
* #param c Context of application
* #return list of installed applications
*/
public static List<PackageInfo> getInstalledApplications(Context c) {
return c.getPackageManager().getInstalledPackages(PackageManager.GET_ACTIVITIES);
}
PackageManager methods, like getInstalledPackages(), can result in a binder transaction error, if the sum total of information being returned is greater than 1MB.
One way to mitigate this is to pass in no flags (e.g., skip PackageManager.GET_ACTIVITIES) to reduce the amount of data in the first call. Then, for those packages where you need the additional detail, call getPackageInfo() to get the details for a specific package. While this does involve multiple IPC round-trips, and therefore is slower, it will help prevent you from blowing out the 1MB-per-transaction limit.
It turned out that I was recieving too much information from the packageManager when I was getting the list of installed applications i.e.
Utilities.getInstalledApplications(this)
In my Utilities class. So then I thought that instead of getting ALL of the installed applications, that I should just get the users installed applications (excluding the system ones that are pointless for my use anyways). Here is the updated class:
public class Utilities {
/*
* Get all installed application on mobile and return a list
* #param c Context of application
* #return list of installed applications
*/
public static List<ResolveInfo> getInstalledApplications(Context c) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
return c.getPackageManager().queryIntentActivities(intent, PackageManager.GET_ACTIVITIES);
}
Then of course any list with
<PackageInfo>
had to be changed to
<ResolveInfo>
but it worked like a charm!

Retrieve item from Spinner and put Some conditions

i have 2 arrays first for Hours and second for minutes, this is my arrays declare it in string.xml
` <string-array name="feedbacktypelist">
<item>#string/hr0</item>
<item>#string/hr1</item>
<item>#string/hr2</item>
</string-array>
<string-array name="array2">
<item>#string/min5</item>
<item>#string/min10</item>
<item>#string/min15</item>
<item>#string/min20</item>
<item>#string/min25</item>
<item>#string/min30</item>
<item>#string/min35</item>
<item>#string/min40</item>
<item>#string/min45</item>
<item>#string/min50</item>
<item>#string/min55</item>
<item>#string/min59</item>
</string-array>`
and this is my code in java
package lmp.app.pkg;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class CreateNewForm extends Activity implements OnItemSelectedListener {
Button Browse;
ImageView CasePic;
Spinner CaseDurationH, CaseDurationM;
TextView tesst;
RadioGroup GenderSelection;
EditText CaseName, CaseClothes, CaseMoreInfo, CaseAge;
Button Next;
//For Browsering Picture
private static final int SELECT_PICTURE = 1;
private String selectedImagePath;
#Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.create_new_form);
//To Call initializer Function
initializer();
//j list
// 1-For Uploading Picture
Browse.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
// in onCreate or any event where your want the user to
// select a file
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select Picture"), SELECT_PICTURE);
}
});
// 1-Name
final MyCase case1 = new MyCase();
case1.setName(CaseName.getText().toString());
// 2-Gender For Group Radio
GenderSelection.clearCheck();
GenderSelection.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.radio0:
case1.setGender("Male");
break;
case R.id.radio1:
case1.setGender("Female");
break;
default:
break;
}
}
});
//3-Age
String age = CaseAge.getText().toString();
/*int tstnum =case1.getAge();
tesst.setText(tstnum); */
//4-Duration Time
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.feedbacktypelist, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
CaseDurationH.setAdapter(adapter);
//5-Case Clothes
case1.setClothes(CaseClothes.getText().toString());
//6-Case More Information
case1.setMoreInfo(CaseMoreInfo.getText().toString());
//Move to 2nd form page
Next= (Button)findViewById(R.id.Next2);
Next.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case R.id.Next2:
try
{
Intent k = new Intent(CreateNewForm.this, CreateNewForm_2.class);
startActivity(k);
}catch(Exception e){
}
break;
}
}
});
//Spinner
CaseDurationH.setOnItemSelectedListener(new OnItemSelectedListener() {
int i =CaseDurationH.getSelectedItemPosition();
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
int i = CaseDurationH.getSelectedItemPosition();
if(i==2){
CaseDurationM.setEnabled(false);
}
String str = parent.getSelectedItem().toString();
if(str.equals("hr0"))
{
}
if(str.equals("hr1"))
{
}
if(str.equals("hr2"))
{
CaseDurationM.setEnabled(false);
}
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
} });
}
// To initialize the variables
private void initializer() {
// TODO Auto-generated method stub
//This information will be filled by a user
//CasePic = (ImageView) findViewById(R.id.imageView1);
CaseName= (EditText) findViewById(R.id.caseNm);
GenderSelection= (RadioGroup) findViewById(R.id.radioGroup1);
CaseAge= (EditText) findViewById(R.id.caseaage);
tesst= (TextView) findViewById(R.id.textView8);
CaseDurationH= (Spinner) findViewById(R.id.Shr);
CaseDurationM= (Spinner) findViewById(R.id.Smin);
CaseClothes= (EditText) findViewById(R.id.caseClothes);
CaseMoreInfo= (EditText) findViewById(R.id.caseMrInfo);
CasePic = (ImageView) findViewById(R.id.casepic);
Browse = (Button) findViewById(R.id.browseCasePic);
}
//For Uploading Picture
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
}
}
}
//For Uploading Picture
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
i want:
1- retrieve the item in spinner that the user choose it, not the positon
2-if the user choose from spinner1 the item "hr02" then the spinner2 will disable
Thank you for help me, StackOverFlow members your my hero now! :")
use this
String str = parent.getSelectedItem().toString();
if(str.equals("hr2")
{
spinner2.setEnabled(false);
}
Try this:
String str = parent.getSelectedItem().toString();
if (str.equals("hr0")){
//retrieve the item as string
}
if (str.equals("hr1")){
//retrieve the item as string
}
if (str.equals("hr2")){
//retrieve the item as string
//make the 2nd spinner disable
}

Categories

Resources