I'm working on an app similar to a gallery, and I'm trying delete option. As suggested in other threads I tried to use media scan after deleting but for some unknown reason, it is not working. The file is getting deleted but in my app, it is showing a file is still there.
In other Gallery APPS I can see the file being deleted, but even after uninstalling my app and re-installing, in list file is available but on click of it I get an empty screen for preview.
This is my activity :
package com.example.sumukha.galleri.Activities;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.BaseColumns;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.example.sumukha.galleri.Adapter.FullScreenImageAdapter;
import com.example.sumukha.galleri.R;
import com.example.sumukha.galleri.Utils.Function;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
public class FullScreenImageActivity extends AppCompatActivity {
ArrayList<HashMap<String, String>> imageList = new ArrayList<HashMap<String, String>>();
String imagePath;
int position;
ArrayList<String> allPaths;
private FullScreenImageAdapter adapter;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_full_screen_image);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
imageList = (ArrayList<HashMap<String, String>>) getIntent().getSerializableExtra("list");
imagePath = getIntent().getStringExtra("path");
position = getIntent().getIntExtra("position",0);
viewPager = findViewById(R.id.media_pager);
updatePageTitle(position);
allPaths = new ArrayList<>();
System.out.println("******* imageList.size() "+imageList.size());
for(int i=0; i<imageList.size();i++){
allPaths.add(imageList.get(i).get(Function.KEY_PATH));
System.out.println("******* path at "+i+" is "+imageList.get(i).get(Function.KEY_PATH));
}
adapter = new FullScreenImageAdapter(FullScreenImageActivity.this,
allPaths);
viewPager.setAdapter(adapter);
// displaying selected image first
viewPager.setCurrentItem(position);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
updatePageTitle(position);
imagePath = imageList.get(position).get(Function.KEY_PATH);
System.out.println("******* new path "+imagePath);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
private void updatePageTitle(int position) {
getSupportActionBar().setTitle(getString(R.string.of, (position+1), imageList.size()));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
this.finish();
return true;
case R.id.action_share :
shareImage(imagePath);
//Toast.makeText(FullScreenImageActivity.this,"ABt to share",Toast.LENGTH_SHORT).show();
break;
case R.id.action_settings :
Toast.makeText(FullScreenImageActivity.this,"ABt d pic..",Toast.LENGTH_SHORT).show();
break;
case R.id.fav_image :
Toast.makeText(FullScreenImageActivity.this,"Mark himmmm",Toast.LENGTH_SHORT).show();
break;
case R.id.delete_image :
deleteImage(imagePath);
//Toast.makeText(FullScreenImageActivity.this,"ABt to delete",Toast.LENGTH_SHORT).show();
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.viewimage_menu, menu);
return true;
}
public void shareImage(String filePath){
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/*");
Uri uri = Uri.fromFile(new File(filePath));
share.putExtra(Intent.EXTRA_STREAM, Uri.parse(String.valueOf(uri)));
startActivity(Intent.createChooser(share, "Share Image"));
Uri.fromFile(new File(filePath));
}
public void deleteImage(String filePath) {
System.out.println("******* imgpth recvd to delete "+filePath);
//String file_dj_path = filePath;
String smallPath = filePath.substring(19);
File fdelete = new File(Environment.getExternalStorageDirectory()+smallPath);
if (fdelete.exists()) {
if (fdelete.delete()) {
System.out.println("******* imgpth deleted "+filePath);
callBroadCast();
} else {
System.out.println("******* imgpth not deleted "+filePath);
}
}
}
public void callBroadCast() {
if (Build.VERSION.SDK_INT >= 14) {
System.out.println("******* callBroadCast > 14");
MediaScannerConnection.scanFile(this, new String[]{Environment.getExternalStorageDirectory().toString()}, null, new MediaScannerConnection.OnScanCompletedListener() {
/*
* (non-Javadoc)
* #see android.media.MediaScannerConnection.OnScanCompletedListener#onScanCompleted(java.lang.String, android.net.Uri)
*/
public void onScanCompleted(String path, Uri uri) {
System.out.println("******* Scanned "+path);
System.out.println("******* uri "+uri);
}
});
} else {
System.out.println("******* SDK < 14 ");
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory())));
}
}
}
Related
I have menu item in MainActivity it is filter(sort), I want that if user click on filter menu like A-z or z-a, in my MainActivity's onclick it is clicked but i want to get acknowledge in fragments as well
[nhewuhfduehiuhuewhucuewcueucueuncneincineincinencneincineinciniencineicnnecnnecneicniencnnecncncncnicnincincncnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnncncicieicieicicnicnncncicn]
code:
MainActivity:
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.style.TextAppearanceSpan;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.navigation.NavigationView;
import com.google.android.material.tabs.TabLayout;
import com.tekitsolutions.remindme.Adapter.ReminderListAdapter;
import com.tekitsolutions.remindme.Adapter.ViewPagerAdapter;
import com.tekitsolutions.remindme.Fragment.HomeFragment;
import com.tekitsolutions.remindme.Fragment.OfficeFragment;
import com.tekitsolutions.remindme.Fragment.OtherFragment;
import com.tekitsolutions.remindme.Interface.AdapterInterface;
import com.tekitsolutions.remindme.Interface.HamburgerMenuInterface;
import com.tekitsolutions.remindme.Interface.MenuItemListener;
import com.tekitsolutions.remindme.Interface.SearchListener;
import com.tekitsolutions.remindme.Model.General;
import com.tekitsolutions.remindme.Model.ParticularPayment;
import com.tekitsolutions.remindme.Model.Profile;
import com.tekitsolutions.remindme.Model.Reminder;
import com.tekitsolutions.remindme.R;
import com.tekitsolutions.remindme.RestApi.ApiClient;
import com.tekitsolutions.remindme.RestApi.ApiInterface;
import com.tekitsolutions.remindme.Sql.DatabaseAdapter;
import com.tekitsolutions.remindme.Utils.RemindMe;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static com.tekitsolutions.remindme.Utils.CommonUtils.CREATE_PASSCODE_ACTIVITY;
import static com.tekitsolutions.remindme.Utils.CommonUtils.GET_PROFILE;
import static com.tekitsolutions.remindme.Utils.CommonUtils.IMAGE;
import static com.tekitsolutions.remindme.Utils.CommonUtils.PHONE_NUMBER;
import static com.tekitsolutions.remindme.Utils.CommonUtils.PICK_SEARCH;
import static com.tekitsolutions.remindme.Utils.CommonUtils.PROFILE;
import static com.tekitsolutions.remindme.Utils.CommonUtils.USERNAME;
public class MainActivity extends BaseActivity implements NavigationView.OnNavigationItemSelectedListener, AdapterInterface, HamburgerMenuInterface, SearchListener, MenuItemListener {
private static final String TAG = MainActivity.class.getSimpleName();
#BindView(R.id.toolbar)
Toolbar toolbar;
#BindView(R.id.recycler_view)
RecyclerView listView;
private String phoneNum = null, getImage = null, getUsername = null;
private int first = 0, position = 0;
private ActionBar actionBar;
private DatabaseAdapter dbAdapter;
private ReminderListAdapter listAdapter;
private List<Reminder> listItems = new ArrayList<>();
private TabLayout tabLayout;
private ViewPager viewPager;
private MenuItemListener searchListener;
private DrawerLayout drawer;
private SharedPreferences profilePreference;
private TextView navUsername, navMobile;
private ImageView navImage;
private View headerView;
private NavigationView navigationView;
private SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
CREATE_PASSCODE_ACTIVITY = 0;
setThemeAndLoadLocale(MainActivity.this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
ButterKnife.bind(this);
setToolbar(toolbar, getString(R.string.app_name));
profilePreference = getSharedPreferences(PROFILE, MODE_PRIVATE);
getDataPhoneNumber();
tabLayout = findViewById(R.id.tab_layout);
viewPager = findViewById(R.id.view_pager);
drawer = findViewById(R.id.drawer_layout);
navigationView = findViewById(R.id.nav_view);
headerView = navigationView.getHeaderView(0);
navUsername = headerView.findViewById(R.id.profile_name);
navMobile = headerView.findViewById(R.id.mobile_number);
navImage = headerView.findViewById(R.id.profile_image);
if (!phoneNum.isEmpty()) {
first = 1;
getProfileData();
}
Menu menu = navigationView.getMenu();
MenuItem tools = menu.findItem(R.id.nav_general_setting);
SpannableString s = new SpannableString(tools.getTitle());
s.setSpan(new TextAppearanceSpan(this, R.style.nav_header_color), 0, s.length(), 0);
tools.setTitle(s);
Menu menu2 = navigationView.getMenu();
MenuItem tools2 = menu2.findItem(R.id.nav_communicate);
SpannableString s2 = new SpannableString(tools2.getTitle());
s2.setSpan(new TextAppearanceSpan(this, R.style.nav_header_color), 0, s2.length(), 0);
tools2.setTitle(s2);
navigationView.setNavigationItemSelectedListener(this);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.AddFragment(new HomeFragment(), getResources().getString(R.string.fragment_home));
adapter.AddFragment(new OfficeFragment(), getResources().getString(R.string.fragment_office));
adapter.AddFragment(new OtherFragment(), getResources().getString(R.string.fragment_other));
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
listAdapter = new ReminderListAdapter(this, listItems, MainActivity.this, this, this);
listView.setHasFixedSize(true);
final LinearLayoutManager mLayoutManager;
mLayoutManager = new LinearLayoutManager(this);
listView.setLayoutManager(mLayoutManager);
listView.setItemAnimator(new DefaultItemAnimator());
try {
listView.setAdapter(listAdapter);
} catch (Exception exp) {
exp.printStackTrace();
}
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this, AddReminderActivity.class));
}
});
dbAdapter = new DatabaseAdapter(this);
HomeFragment homeFragment = new HomeFragment();
homeFragment.setListener(this);
}
#Override
public void onClickFavoriteById(int isFavorite, long id) {
}
private void setData() {
if (getUsername != null && !getUsername.isEmpty()) {
navUsername.setText(getUsername.trim());
}
if (phoneNum != null && !phoneNum.isEmpty()) {
navMobile.setVisibility(View.VISIBLE);
navMobile.setText(phoneNum);
}
if (getImage != null && !getImage.isEmpty()) {
Bitmap bitmap = convertBase64ToBitMap(getImage);
navImage.setImageBitmap(bitmap);
} else {
navImage.setImageResource(R.drawable.user_image);
}
}
private void storeInSharedPreference() {
editor = getSharedPreferences(PROFILE, MODE_PRIVATE).edit();
editor.putString(USERNAME, getUsername);
editor.putString(IMAGE, getImage);
editor.apply();
}
private void getProfileData() {
ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class);
Call<List<Profile>> profileDetails = apiInterface.getProfileDetails(phoneNum);
profileDetails.enqueue(new Callback<List<Profile>>() {
#Override
public void onResponse(Call<List<Profile>> call, Response<List<Profile>> response) {
int statusCode = response.code();
if (statusCode == 200) {
List<Profile> responseList = response.body();
Profile profile = responseList.get(0);
showLog("username: " + profile.getProfileName());
getUsername = profile.getProfileName();
if (getUsername == null) {
showLog("Null");
} else {
showLog("Not null");
}
getImage = profile.getImage();
phoneNum = profile.getProfileNo();
setData();
storeInSharedPreference();
}
}
#Override
public void onFailure(Call<List<Profile>> call, Throwable t) {
showLog("Failed: " + t.getMessage());
}
});
}
private void getDataFromSharedPref() {
phoneNum = profilePreference.getString(PHONE_NUMBER, "");
getUsername = profilePreference.getString(USERNAME, "");
getImage = profilePreference.getString(IMAGE, "");
}
private void getDataPhoneNumber() {
phoneNum = profilePreference.getString(PHONE_NUMBER, "");
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Intent intent = null;
switch (item.getItemId()) {
case R.id.nav_profile:
intent = new Intent(this, ProfileActivity.class);
intent.putExtra(GET_PROFILE, true);
intent.putExtra(IMAGE, getImage);
intent.putExtra(USERNAME, getUsername);
startActivity(intent);
break;
case R.id.nav_favorite:
intent = new Intent(MainActivity.this, AddFavoriteReminder.class);
startActivity(intent);
break;
case R.id.nav_setting:
intent = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(intent);
break;
case R.id.nav_passcode:
intent = new Intent(this, PasscodeActivity.class);
startActivity(intent);
break;
case R.id.nav_share:
String link = "https://drive.google.com/drive/folders/1sDS_hGb5s5SjyDIK3me3oY8cS1Oo1I4F?usp=sharing";
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
SpannableString ss = new SpannableString("Android is a Software stack");
String shareBodyText = link;
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject here");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBodyText);
startActivity(Intent.createChooser(sharingIntent, "Sharing Option"));
return true;
case R.id.nav_help:
intent = new Intent(MainActivity.this, HelpActivity.class);
startActivity(intent);
break;
case R.id.nav_feedback:
intent = new Intent(Intent.ACTION_SENDTO);
intent.setType("message/rfc822");
intent.setData(Uri.parse("mailto:"));
intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"jimmytrivedi#outlook.com"});
intent.putExtra(Intent.EXTRA_SUBJECT, "Remind Me Feedback");
intent.putExtra(Intent.EXTRA_TEXT, "Developer Team,");
try {
startActivity(Intent.createChooser(intent, "Send Email"));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(MainActivity.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public void onClickReminderList(int position) {
}
private Bitmap convertBase64ToBitMap(String profileImage) {
try {
byte[] encodeByte = Base64.decode(profileImage, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
return bitmap;
} catch (Exception e) {
showLog("" + e.getMessage());
return null;
}
}
#Override
protected void onResume() {
super.onResume();
CREATE_PASSCODE_ACTIVITY = 0;
if (RemindMe.isChanged()) {
RemindMe.setChanged(false);
recreate();
}
getDataFromSharedPref();
setData();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.search:
Intent intent = new Intent(MainActivity.this, SearchActivity.class);
startActivityForResult(intent, PICK_SEARCH);
break;
case R.id.filter:
break;
case R.id.ascending:
position = 1;
break;
case R.id.descending:
position = 2;
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_fragment_search, menu);
getMenuInflater().inflate(R.menu.menu_filter, menu);
return true;
}
#Override
public void onClickHamburger(long id) {
}
#Override
public void onClickListItem(int position) {
}
#Override
public void setToolbar(Toolbar toolBar, String title) {
super.setToolbar(toolBar, title);
}
private void showLog(String msg) {
Log.d(TAG, msg);
}
#Override
public void onSelectedProviderSearchItem(General general) {
}
#Override
public void onSelectedParticularPaymentSearchItem(ParticularPayment particularPayment) {
}
#Override
public void onSelectedReminderSearchItem(Reminder reminder) {
}
#Override
public void unused(int position) {
}
#Override
public void onFilterItem(int position) {
}
}
Interface
MenuItemListener
import com.tekitsolutions.remindme.Model.General;
import com.tekitsolutions.remindme.Model.ParticularPayment;
import com.tekitsolutions.remindme.Model.Reminder;
public interface MenuItemListener {
void onFilterItem(int position);
}
HomeFragment:
package com.tekitsolutions.remindme.Fragment;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.tekitsolutions.remindme.Activity.AddReminderActivity;
import com.tekitsolutions.remindme.Activity.MainActivity;
import com.tekitsolutions.remindme.Activity.ReminderDetailActivity;
import com.tekitsolutions.remindme.Adapter.ReminderListAdapter;
import com.tekitsolutions.remindme.Interface.AdapterInterface;
import com.tekitsolutions.remindme.Interface.HamburgerMenuInterface;
import com.tekitsolutions.remindme.Interface.MenuItemListener;
import com.tekitsolutions.remindme.Interface.SearchListener;
import com.tekitsolutions.remindme.Model.General;
import com.tekitsolutions.remindme.Model.ParticularPayment;
import com.tekitsolutions.remindme.Model.Reminder;
import com.tekitsolutions.remindme.R;
import com.tekitsolutions.remindme.Receiver.AlarmReceiver;
import com.tekitsolutions.remindme.RestApi.ApiClient;
import com.tekitsolutions.remindme.RestApi.ApiInterface;
import com.tekitsolutions.remindme.Sql.DatabaseAdapter;
import com.tekitsolutions.remindme.Utils.RecyclerViewClickListener;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static com.tekitsolutions.remindme.Sql.DataBaseConstant.REMINDER_FAVORITE;
import static com.tekitsolutions.remindme.Sql.DataBaseConstant.REMINDER_ID;
import static com.tekitsolutions.remindme.Sql.DataBaseConstant.REMINDER_TYPE_ID;
import static com.tekitsolutions.remindme.Utils.CommonUtils.HOME;
import static com.tekitsolutions.remindme.Utils.CommonUtils.IS_EDIT;
import static com.tekitsolutions.remindme.Utils.CommonUtils.PICK_HOME;
public class HomeFragment extends Fragment implements AdapterInterface, HamburgerMenuInterface, Callback<String>, SearchListener, MenuItemListener {
private static final String TAG = HomeFragment.class.getSimpleName();
public MainActivity activity;
public Context context;
View view;
private DatabaseAdapter dbAdapter;
private List<Reminder> listItems = new ArrayList<>();
private ReminderListAdapter listAdapter;
private MenuItemListener menuItemListener;
private RecyclerView listView;
private TextView tvNoData;
private AdapterInterface listener;
private HamburgerMenuInterface menuInterface;
private AlertDialog.Builder builder;
private Reminder reminder;
private long reminderId = 0;
private int getFavorite = 0;
public HomeFragment() {
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.home_fragment, container, false);
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
listView = view.findViewById(R.id.recycler_view);
tvNoData = view.findViewById(R.id.tv_no_data);
dbAdapter = new DatabaseAdapter(getContext());
listAdapter = new ReminderListAdapter(getActivity(), listItems, HomeFragment.this, this, this);
listView.setHasFixedSize(false);
final LinearLayoutManager mLayoutManager;
mLayoutManager = new LinearLayoutManager(getActivity());
listView.setLayoutManager(mLayoutManager);
listView.setItemAnimator(new DefaultItemAnimator());
try {
listView.setAdapter(listAdapter);
} catch (Exception exp) {
exp.printStackTrace();
}
listView.addOnItemTouchListener(new RecyclerViewClickListener.RecyclerTouchListener(getContext(),
listView, new RecyclerViewClickListener.ClickListener() {
#Override
public void onClick(View view, int position) {
}
#Override
public void onLongClick(View view, int position) {
}
}
));
loadAllReminders();
}
#Override
public void onStart() {
super.onStart();
loadAllReminders();
}
private void loadAllReminders() {
listItems.clear();
List<Reminder> list = dbAdapter.getReminderById(REMINDER_TYPE_ID, HOME);
if (list.size() > 0) {
tvNoData.setVisibility(View.GONE);
listItems.addAll(list);
listAdapter.notifyDataSetChanged();
} else {
tvNoData.setVisibility(View.VISIBLE);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.menuItemListener = (MenuItemListener) getActivity();
}
private void showLog(String msg) {
Log.d(TAG, msg);
}
#Override
public void onFilterItem(int position) {
showLog("test: " + position);
}
public void setListener(MenuItemListener listener) {
this.menuItemListener = listener;
}
}
You can do this with EventBus or Interface. You can follow these steps for EventBus.
Implement EventBus
implementation 'org.greenrobot:eventbus:3.1.1'
EventBustDataEvents.class
public class EventBusDataEvents{
public static class isClick {
boolean isClick;
public isClick(boolean isClick) {
this.isClick = isClick;
}
public boolean getIsClick() {
return isClick;
}
public void setIsClick(boolean isClick) {
this.isClick = isClick;
}
}
}
MainActivity.class
EventBus.getDefault().postSticky(new EventBusDataEvents.isClick(true));
Fragment.class
#Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
public void isClick(EventBusDataEvents.isClick click) {
if (click.isClick()) {
}
}
#Override
public void onStart() {
super.onStart();
try {
EventBus.getDefault().register(this);
} catch (Exception e) {
}
}
#Override
public void onDestroy() {
super.onDestroy();
try {
EventBus.getDefault().unregister(this);
} catch (Exception e) {
}
}
Or Interface
IMainActivity.class // interface class
public interface IMainActivity {
void onClick();}
MainActivity.class
private IMainActivity listener; //This will be described above as a field.
public void setOnEventListener(IMainActivity listener) {
IMainActivity = listener;
}
//buttonClickEvent
listener.OnClick();
Fragment.class
//onCreateView
setOnEventListener(new IMainActivity() {
#Override
public void onClick() {
}
});
In my app, I am trying to add sorting such as: sort by popular, top rated, etc.
with sorting options in AlertDialog.
My problem is that choosing the option to sort by GridView doesn't update or change ImageView
I tried the following but it doesn't work:
adapter.notifyDataSetChanged();
gridView.invalidateViews();
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Point;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.BoolRes;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
/**
* Created by macbook on 9/18/17.
*/
public class MoviesFragment extends Fragment implements AdapterView.OnItemClickListener {
static GridView gridView;
static int width;
static ArrayList<String> posters;
private final static String API_KEY = "0000000000000000000";
final static String URL_BASE = "https://api.themoviedb.org/3/movie/";
static String url_sorted ="popular?api_key=" ;
ImageAdapter adapter;
public MoviesFragment()
{
}
// inflate view and init grideView with set adapter
#Nullable
#Override
public View onCreateView (LayoutInflater inflater, #Nullable ViewGroup
container, #Nullable Bundle savedInstanceState){
View view = inflater.inflate(R.layout.movies_fragment, container, false);
setHasOptionsMenu(true);
// getwidth
WindowManager wm = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
if(MainActivity.TABLET)
{
width = size.x/6;
}else
{
width = size.x/2;
}
if(getActivity() != null)
{
posters = new ArrayList<String>();
adapter = new ImageAdapter(getActivity(),posters,width);
gridView = (GridView)view.findViewById(R.id.grideView);
gridView.setAdapter(adapter);
gridView.setColumnWidth(width);
gridView.setOnItemClickListener(this);
}
return view;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getActivity(),position+"",Toast.LENGTH_SHORT).show();
}
#Override
public void onStart() {
super.onStart();
getActivity().setTitle("Most Popular Movies");
loadPoster(url_sorted);
}
public void loadPoster(String url) {
if (isNetworkAvailable()) {
gridView.setVisibility(View.VISIBLE);
getJsonImageUrl(url);
} else {
gridView.setVisibility(View.GONE);
TextView text = new TextView(getActivity());
RelativeLayout relativeLayout = (RelativeLayout) getActivity().findViewById(R.id.relative);
text.setText("no Internet Connection...");
relativeLayout.addView(text);
}
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
public Boolean getJsonImageUrl( String urlSort)
{
Toast.makeText(getActivity(),urlSort,Toast.LENGTH_LONG).show();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, URL_BASE + urlSort+ API_KEY, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
int count = 0 ;
JSONArray obj = null;
try {
obj = response.getJSONArray("results");
} catch (JSONException e) {
e.printStackTrace();
}
while(count <obj.length())
{
JSONObject jsonObject = null;
String imgURL = null;
try {
jsonObject = obj.getJSONObject(count);
imgURL = jsonObject.getString("poster_path");
} catch (JSONException e) {
e.printStackTrace();
}
posters.add(imgURL);
count++;
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(),"ERROR",Toast.LENGTH_LONG).show();
}
}
);
Mysingleton.getInstence(getContext()).addToRequestque(jsonObjectRequest);
return true;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId())
{
case R.id.preferncesMenu:
break;
case R.id.filter:
// Intent i = new Intent(getActivity().getApplication(),SettingAactivity.class);
//startActivity(i);
showSortDialog();
break;
}
return false;
}
private void showSortDialog() {
final CharSequence[] sortBy = new String[] {"Popular", "Top Rated","Latest","Upcoming","Now playing"};
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Sort by");
builder.setSingleChoiceItems(sortBy, -1, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String newUrl;
gridView.setAdapter(null);
switch(which)
{
case 0:
newUrl = "popular?api_key=";
getActivity().setTitle("Most Popular Movies");
//loadPoster(newUrl);
break;
case 1:
newUrl = "top_rated?api_key=";
getActivity().setTitle("Top Rated Movies");
adapter.notifyDataSetChanged();
gridView.invalidateViews();
loadPoster(newUrl);
Toast.makeText(getActivity(),newUrl,Toast.LENGTH_LONG).show();
dialog.dismiss();
break;
case 2:
url_sorted = "latest?api_key=";
getActivity().setTitle("latest Movies");
break;
case 3:
url_sorted = "upcoming?api_key=";
getActivity().setTitle("UpComing Movies");
break;
case 5:
url_sorted = "now_playing?api_key=";
getActivity().setTitle("Now Playing Movies");
break;
}
}
});
builder.create().show();
}
}
The problem was calling notifyDataSetChanged() from a non UI Thread.
So after call notifyDataSetChanged() from UI Thread its work perfectly
Code:
public void refresh()
{
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
adapter.notifyDataSetChanged();
gridView.invalidate();
}
});
}
Basically inside your adapter you need to have mechanism to pass in/update the data object.
Add a method inside your adapter class which will be called when new data is available.
public void swapItems(List<Item> itemsList){
mItemsList.clear();
mItemsList.addAll(itemsList);
notifyDataSetChanged();
}
Then from your activity, after you have received your new data, just call this method from your adapter instance.
adapter.swapItems(newItemsList);
Just change the above code to match your data type. But that's basically how it's done. And if you want to be more fancy explore Android data binding.
I only see you calling notifyDataSetChanged after you set the adapter to null. I'm not sure why you would set the adapter to null and then attempt to use it. You should be crashing, not just seeing data not updated.
After your getjson call you should be calling notifyDataSetChanged to show all the new items you got. If sort is to change the sort order, then you should implement your sort on the list, then call notifyDataSetChanged again.
I'm not sure why you are nulling it out. If you do this, you should be fine.
I have this custom Loader that is supposed to insert some dummy data I sent to it in a database using content resolver. I'm using the getLoaderManager().initLoader(INSERT_DUMMY_DATA_ID, null, this);
in the activity. The constructor gets called. But the onStartLoading() and loadinBackgroung() arent called.
Here is the ProductInsertionLoader.java
public class ProductInsertionLoader extends AsyncTaskLoader {
private String LOG_TAG = ProductInsertionLoader.class.getSimpleName();
private ArrayList<ContentValues> mValues;
private ContentResolver mContentResolver;
public ProductInsertionLoader(Context context, ContentResolver contentResolver, ArrayList<ContentValues> values) {
super(context);
mValues = values;
mContentResolver = contentResolver;
Log.v(LOG_TAG, "constructor called");
}
#Override
public Object loadInBackground() {
Log.v(LOG_TAG, "loadInBackground() called");
ArrayList<Uri> uris = new ArrayList<>();
for (ContentValues value : mValues) {
Uri uri = mContentResolver.insert(ProductContract.ProductEntry.CONTENT_URI, value);
Log.v(LOG_TAG, "Dummy data inserted. ID: " + ContentUris.parseId(uri));
uris.add(uri);
}
return null;
}
#Override
protected void onStartLoading() {
Log.v(LOG_TAG, "onStartLoading() called");
forceLoad();
}
}
Here is how I'm calling it in the CatalogActivity.java
package com.example.android.inventory;
import android.app.LoaderManager;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.CursorLoader;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.android.inventory.data.ProductContract.ProductEntry;
import com.example.android.inventory.data.ProductInsertionLoader;
import java.io.IOException;
import java.util.ArrayList;
public class CatalogActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> {
private static final String LOG_TAG = CatalogActivity.class.getSimpleName();
private ProductCursorAdapter mCursorAdapter;
private static final int URL_LOADER = 0;
private static final int INSERT_DUMMY_DATA_ID = 1;
private Uri mCurrentProductUri;
private ArrayList<ContentValues> mValues;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_catalog);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(CatalogActivity.this, EditorActivity.class);
startActivity(intent);
}
});
final ListView listView = (ListView) findViewById(R.id.list_view_product);
TextView textView = (TextView) findViewById(R.id.empty_view);
listView.setEmptyView(textView);
mCursorAdapter = new ProductCursorAdapter(this, null, getContentResolver());
listView.setAdapter(mCursorAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(CatalogActivity.this, EditorActivity.class);
Uri currentProductUri = ContentUris.withAppendedId(ProductEntry.CONTENT_URI, id);
intent.setData(currentProductUri);
startActivity(intent);
}
});
getLoaderManager().initLoader(URL_LOADER, null, CatalogActivity.this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_catalog, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_insert_dummy_data:
insertDummyData();
return true;
case R.id.action_delete_all_entries:
showDeleteConfirmationDialog("Delete all products?", null);
return true;
}
return super.onOptionsItemSelected(item);
}
private void insertDummyData() {
mValues = new ArrayList<>();
mValues.add(getContentValues("Sugar", 50, 60, "Sweet Sugar Company", R.drawable.sugar));
mValues.add(getContentValues("Salt", 20, 30, "Salty Salt Company", R.drawable.salt));
mValues.add(getContentValues("Bread", 45, 20, "Nanglo", R.drawable.bread));
mValues.add(getContentValues("Biscuit", 75, 20, "GoodDay", R.drawable.biscuit));
mValues.add(getContentValues("Noodles", 15, 200, "CupMen", R.drawable.noodles));
mValues.add(getContentValues("Milk", 33, 100, "DDC", R.drawable.milk));
mValues.add(getContentValues("Cheese", 80, 30, "Amul", R.drawable.cheese));
getLoaderManager().initLoader(INSERT_DUMMY_DATA_ID, null, this).forceLoad();
Toast.makeText(this, "Dummy Data Inserted", Toast.LENGTH_SHORT).show();
}
private ContentValues getContentValues(String name, int price, int quantity, String supplier, int resId) {
ContentValues values = new ContentValues();
values.put(ProductEntry.COLUMN_NAME, name);
values.put(ProductEntry.COLUMN_PRICE, price);
values.put(ProductEntry.COLUMN_QUANTITY, quantity);
values.put(ProductEntry.COLUMN_SUPPLIER, supplier);
//Uri for the sugar drawable
Uri imageUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE +
"://" + getResources().getResourcePackageName(resId)
+ '/' + getResources().getResourceTypeName(resId)
+ '/' + getResources().getResourceEntryName(resId));
Bitmap bitmap = null;
//Converting the sugar image into a thumbnail
try {
bitmap = DbBitmapUtility.getThumbnail(imageUri, this);
} catch (IOException e) {
e.printStackTrace();
}
//Converting the sugar thumbnail into a byte array.
byte[] image = DbBitmapUtility.getBitmapAsByteArray(bitmap);
values.put(ProductEntry.COLUMN_IMAGE, image);
return values;
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
switch (id) {
case URL_LOADER:
String[] projection = {
ProductEntry._ID,
ProductEntry.COLUMN_NAME,
ProductEntry.COLUMN_QUANTITY,
ProductEntry.COLUMN_PRICE,
ProductEntry.COLUMN_SUPPLIER,
ProductEntry.COLUMN_IMAGE
};
return new CursorLoader(
this,
ProductEntry.CONTENT_URI,
projection,
null,
null,
null);
case INSERT_DUMMY_DATA_ID:
new ProductInsertionLoader(this, getContentResolver(), mValues);
return null;
default:
Log.v(LOG_TAG, "onCreateLoader: Invalid id");
return null;
}
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
if (loader.getId() == URL_LOADER) {
mCursorAdapter.swapCursor(data);
} else return;
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
mCursorAdapter.swapCursor(null);
}
}
As you can see I'm using two loaders. One CursorLoader to load all the database data into the UI, and a second custom AsyncTaskLoader to insert some dummy data on to the database on a background thread.
Why isn't the custom loader's onStartLoading() or loadInBackground() not being called?
I need to take photo and send in MainActivity and send it to thirdActivity
this is the code of MainActivity
PS : I opened Main activity From ThirdActivity
package com.fakecamera.hassanechafai.fakacamera;
import java.io.File;
import com.fakecamera.hassanechafai.fakacamera.R;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.PictureCallback;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import com.fakecamera.hassanechafai.fakacamera.CameraPreview;
import com.fakecamera.hassanechafai.fakacamera.MyAlertDialogs;
import com.fakecamera.hassanechafai.fakacamera.NoCameraPresentDialog;
public class MainActivity extends Activity {
private Camera mCamera;
private CameraPreview mCameraPreview;
public static Display display;
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay();
mCamera = this.getCameraInstance();
if (mCamera == null) {
NoCameraPresentDialog noCamera = new NoCameraPresentDialog(
MainActivity.this);
noCamera.showDialog();
} else {
mCameraPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mCameraPreview);
ImageButton captureButton = (ImageButton) findViewById(R.id.button_capture);
captureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCamera.takePicture(null, null, mPicture);
// mCamera.startPreview();
}
});
}
}
private Camera getCameraInstance() {
Camera camera = null;
Log.d("No of cameras", Camera.getNumberOfCameras() + "");
for (int camNo = 0; camNo < Camera.getNumberOfCameras(); camNo++) {
CameraInfo camInfo = new CameraInfo();
Camera.getCameraInfo(camNo, camInfo);
if (camInfo.facing == (Camera.CameraInfo.CAMERA_FACING_FRONT)) {
camera = Camera.open(camNo);
}
}
return camera;
}
PictureCallback mPicture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
notifyImageCapture(pictureFile.getPath());
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
};
public void notifyImageCapture(String filepath) {
Intent i = new Intent(this, ThirdActivity.class);
i.putExtra("path", "" + filepath);
startActivityForResult(i, 100);
}
public static File getOutputMediaFile() {
File mediaStorageDir = new File(
Environment.getExternalStorageDirectory(), "Photos");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("Photos", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
Log.i("Mediapath", "" + mediaFile.getPath());
return mediaFile;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (requestCode == 100) {
this.finish();
startActivity(new Intent(this, MainActivity.class));
}
super.onActivityResult(requestCode, resultCode, data);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
MyAlertDialogs dialogs = new MyAlertDialogs(MainActivity.this);
dialogs.getRateMyAppDialog();
}
return super.onKeyDown(keyCode, event);
}
}
this is my code of thirdActivity
package com.fakecamera.hassanechafai.fakacamera;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.content.Intent;
import android.os.Handler;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.graphics.Bitmap;
import com.fakecamera.hassanechafai.fakacamera.LoadImageBitmap;
public class ThirdActivity extends ActionBarActivity {
private ImageView imageToEdit;
private Bitmap orignalBitmap;
private String CLICKED_IMAGE_FILE_PATH;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
ImageButton takeimage = (ImageButton)findViewById(R.id.imageButton3);
takeimage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ThirdActivity.this,
MainActivity.class);
startActivity(intent);
}
});
imageToEdit = (ImageView) this.findViewById(R.id.item_click_image);
final EditText edittext = (EditText)findViewById(R.id.editText);
Button button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int time = Integer.parseInt(edittext.getText().toString());
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent startActivity = new Intent(ThirdActivity.this, FullscreenActivity.class);
startActivity(startActivity);
finish();
}
}, time * 1000);
}
});
CLICKED_IMAGE_FILE_PATH = getIntent().getStringExtra("path");
this.setUpImage(CLICKED_IMAGE_FILE_PATH);
}
public void setUpImage(String path) {
LoadImageBitmap imageLoader = new LoadImageBitmap();
orignalBitmap = imageLoader.displayFullImage(path);
if(CameraPreview.isPortrait){
orignalBitmap = ImageEffects.rotate(imageLoader.displayFullImage(path));
}else{
orignalBitmap=imageLoader.displayFullImage(path);
}
imageToEdit.setImageBitmap(orignalBitmap);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_third, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I have any error but when I trying to take a photo I get this message :
Unfortunately ,FirstCamera has stopped
what is my problem ?
You should call startActivityForResult from ThirdActivity and then set the photo as result in your MainActivity. For this you will need to make sure your photo model implements Parcelable.
You can then call setResult(RESULT_OK, Photo) in MainActivity and you will get the photo back in ThirdActivity in the method onActivityResult
If your photo is too large, you should convert it to bytes array to put it to Intent
I'm doing a aplication to recorder the sound, but when I try to record the sound,the emulator is stopped because it ask me to insert an SD card. What I have to do? I couldn't do without an SD card ?
Thank you!
package proiektua.proiektua;
import java.io.FileDescriptor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
public class MainActivity extends Activity {
int peticion = 1;
Uri url1;
private int STATE_CONFIGURE;
private int mState = STATE_CONFIGURE;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void grabar(View v) {
Intent intent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
startActivityForResult(intent, peticion);}
public void setOutputFile(FileDescriptor fd) {
switch (mState) {
case STATE_RECORD:
throw new RuntimeException("setOutputFile cannot be called while recording!");
case STATE_RELEASED:
throw new RuntimeException("setOutputFile called on an already released recorder!");
default:
break;
}
}
public void reproducir(View v) {
MediaPlayer mediaPlayer = MediaPlayer.create(this, url1);
mediaPlayer.start();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == peticion) {
url1 = data.getData();
}
}
}
You have the option to create an SDCard through the mksdcard command and associate it with the amulator.
please look at this function:
public void setOutputFile (FileDescriptor fd)
Added in API level 3
Pass in the file descriptor of the file to be written. Call this after setOutputFormat() but before prepare().
You can decide where to store the file.
also look at this example.
http://androidfreakers.blogspot.co.il/2011/09/using-mediarecorder.html