getActivity() cannot find symbol symbol : method getActivity() - android

I need help with this file for my mms app. getActivity() causes an error in the build.
Error: cannot find symbol: method getActivity()
I have tried numerous things to make this work so far, like extends PreferenceFragment - then getActivity() is fine, but this solution breaks tons of other stuff.
Does anyone know why I'm getting this error?
My code:
package com.android.mms.themes;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.os.SystemProperties;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.preference.PreferenceGroup;
import android.preference.PreferenceManager;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceScreen;
import android.provider.MediaStore;
import android.text.Spannable;
import android.util.Log;
import android.view.Display;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import com.android.mms.R;
import com.android.mms.ui.ColorPickerPreference;
public class ThemesMessageList extends PreferenceActivity implements
Preference.OnPreferenceChangeListener {
// Menu entries
private static final int THEMES_RESTORE_DEFAULTS = 1;
// Layout Style
public static final String PREF_TEXT_CONV_LAYOUT = "pref_text_conv_layout";
// Msg background
public static final String PREF_MESSAGE_BG = "pref_message_bg";
private static final String CUSTOM_IMAGE = "message_list_image.jpg";
private static final int REQUEST_PICK_WALLPAPER = 201;
private static final int SELECT_WALLPAPER = 5;
// Bubble types
public static final String PREF_BUBBLE_TYPE = "pref_bubble_type";
public static final String PREF_BUBBLE_FILL_PARENT = "pref_bubble_fill_parent";
// Checkbox preferences
public static final String PREF_USE_CONTACT = "pref_use_contact";
public static final String PREF_SHOW_AVATAR = "pref_show_avatar";
// Colorpicker preferences send
public static final String PREF_SENT_TEXTCOLOR = "pref_sent_textcolor";
public static final String PREF_SENT_CONTACT_COLOR = "pref_sent_contact_color";
public static final String PREF_SENT_DATE_COLOR = "pref_sent_date_color";
public static final String PREF_SENT_TEXT_BG = "pref_sent_text_bg";
public static final String PREF_SENT_SMILEY = "pref_sent_smiley";
// Colorpicker preferences received
public static final String PREF_RECV_TEXTCOLOR = "pref_recv_textcolor";
public static final String PREF_RECV_CONTACT_COLOR = "pref_recv_contact_color";
public static final String PREF_RECV_DATE_COLOR = "pref_recv_date_color";
public static final String PREF_RECV_TEXT_BG = "pref_recv_text_bg";
public static final String PREF_RECV_SMILEY = "pref_recv_smiley";
// message background
ColorPickerPreference mMessageBackground;
// send
ColorPickerPreference mSentTextColor;
ColorPickerPreference mSentDateColor;
ColorPickerPreference mSentContactColor;
ColorPickerPreference mSentTextBgColor;
ColorPickerPreference mSentSmiley;
// received
ColorPickerPreference mRecvTextColor;
ColorPickerPreference mRecvContactColor;
ColorPickerPreference mRecvDateColor;
ColorPickerPreference mRecvTextBgColor;
ColorPickerPreference mRecvSmiley;
private CheckBoxPreference mUseContact;
private CheckBoxPreference mShowAvatar;
private CheckBoxPreference mBubbleFillParent;
private ListPreference mTextLayout;
private ListPreference mBubbleType;
private Preference mCustomImage;
private SharedPreferences sp;
protected Context mContext;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = getActivity();
loadThemePrefs();
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
}
public void loadThemePrefs() {
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences_themes_msglist);
PreferenceScreen prefSet = getPreferenceScreen();
sp = PreferenceManager.getDefaultSharedPreferences(this);
mUseContact = (CheckBoxPreference) prefSet.findPreference(PREF_USE_CONTACT);
mShowAvatar = (CheckBoxPreference) prefSet.findPreference(PREF_SHOW_AVATAR);
mBubbleFillParent = (CheckBoxPreference) prefSet.findPreference(PREF_BUBBLE_FILL_PARENT);
mTextLayout = (ListPreference) findPreference(PREF_TEXT_CONV_LAYOUT);
mTextLayout.setOnPreferenceChangeListener(this);
mTextLayout.setSummary(mTextLayout.getEntry());
mBubbleType = (ListPreference) findPreference(PREF_BUBBLE_TYPE);
mBubbleType.setOnPreferenceChangeListener(this);
mBubbleType.setSummary(mBubbleType.getEntry());
mCustomImage = findPreference("pref_custom_image");
mMessageBackground = (ColorPickerPreference) findPreference(PREF_MESSAGE_BG);
mMessageBackground.setOnPreferenceChangeListener(this);
mSentTextColor = (ColorPickerPreference) findPreference(PREF_SENT_TEXTCOLOR);
mSentTextColor.setOnPreferenceChangeListener(this);
mSentContactColor = (ColorPickerPreference) findPreference(PREF_SENT_TEXTCOLOR);
mSentContactColor.setOnPreferenceChangeListener(this);
mSentDateColor = (ColorPickerPreference) findPreference(PREF_SENT_TEXTCOLOR);
mSentDateColor.setOnPreferenceChangeListener(this);
mSentTextBgColor = (ColorPickerPreference) findPreference(PREF_SENT_TEXTCOLOR);
mSentTextBgColor.setOnPreferenceChangeListener(this);
mSentSmiley = (ColorPickerPreference) findPreference(PREF_SENT_SMILEY);
mSentSmiley.setOnPreferenceChangeListener(this);
mRecvTextColor = (ColorPickerPreference) findPreference(PREF_RECV_TEXTCOLOR);
mRecvTextColor.setOnPreferenceChangeListener(this);
mRecvContactColor = (ColorPickerPreference) findPreference(PREF_RECV_TEXTCOLOR);
mRecvContactColor.setOnPreferenceChangeListener(this);
mRecvDateColor = (ColorPickerPreference) findPreference(PREF_RECV_TEXTCOLOR);
mRecvDateColor.setOnPreferenceChangeListener(this);
mRecvTextBgColor = (ColorPickerPreference) findPreference(PREF_RECV_TEXT_BG);
mRecvTextBgColor.setOnPreferenceChangeListener(this);
mRecvSmiley = (ColorPickerPreference) findPreference(PREF_RECV_SMILEY);
mRecvSmiley.setOnPreferenceChangeListener(this);
}
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
boolean result = false;
if (preference == mMessageBackground) {
String hex = ColorPickerPreference.convertToARGB(Integer.valueOf(String
.valueOf(newValue)));
mMessageBackground.setSummary(hex);
} else if (preference == mSentTextColor) {
String hex = ColorPickerPreference.convertToARGB(Integer.valueOf(String
.valueOf(newValue)));
mSentTextColor.setSummary(hex);
} else if (preference == mSentContactColor) {
String hex = ColorPickerPreference.convertToARGB(Integer.valueOf(String
.valueOf(newValue)));
mSentContactColor.setSummary(hex);
} else if (preference == mSentDateColor) {
String hex = ColorPickerPreference.convertToARGB(Integer.valueOf(String
.valueOf(newValue)));
mSentDateColor.setSummary(hex);
} else if (preference == mSentTextBgColor) {
String hex = ColorPickerPreference.convertToARGB(Integer.valueOf(String
.valueOf(newValue)));
mSentTextBgColor.setSummary(hex);
} else if (preference == mSentSmiley) {
String hex = ColorPickerPreference.convertToARGB(Integer.valueOf(String
.valueOf(newValue)));
mSentSmiley.setSummary(hex);
} else if (preference == mRecvTextColor) {
String hex = ColorPickerPreference.convertToARGB(Integer.valueOf(String
.valueOf(newValue)));
mRecvTextColor.setSummary(hex);
} else if (preference == mRecvContactColor) {
String hex = ColorPickerPreference.convertToARGB(Integer.valueOf(String
.valueOf(newValue)));
mRecvContactColor.setSummary(hex);
} else if (preference == mRecvDateColor) {
String hex = ColorPickerPreference.convertToARGB(Integer.valueOf(String
.valueOf(newValue)));
mRecvDateColor.setSummary(hex);
} else if (preference == mRecvTextBgColor) {
String hex = ColorPickerPreference.convertToARGB(Integer.valueOf(String
.valueOf(newValue)));
mRecvTextBgColor.setSummary(hex);
} else if (preference == mRecvSmiley) {
String hex = ColorPickerPreference.convertToARGB(Integer.valueOf(String
.valueOf(newValue)));
mRecvSmiley.setSummary(hex);
} else if (preference == mTextLayout) {
int index = mTextLayout.findIndexOfValue((String) newValue);
mTextLayout.setSummary(mTextLayout.getEntries()[index]);
return true;
} else if (preference == mBubbleType) {
int index = mBubbleType.findIndexOfValue((String) newValue);
mBubbleType.setSummary(mBubbleType.getEntries()[index]);
return true;
}
return result;
}
#Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
boolean value;
if (preference == mCustomImage) {
Display display = getActivity().getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
Rect rect = new Rect();
Window window = getActivity().getWindow();
window.getDecorView().getWindowVisibleDisplayFrame(rect);
int statusBarHeight = rect.top;
int contentViewTop = window.findViewById(Window.ID_ANDROID_CONTENT).getTop();
int titleBarHeight = contentViewTop - statusBarHeight;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
intent.setType("image/*");
intent.putExtra("crop", "true");
boolean isPortrait = getResources()
.getConfiguration().orientation
== Configuration.ORIENTATION_PORTRAIT;
intent.putExtra("aspectX", isPortrait ? width : height - titleBarHeight);
intent.putExtra("aspectY", isPortrait ? height - titleBarHeight : width);
intent.putExtra("outputX", width);
intent.putExtra("outputY", height);
intent.putExtra("scale", true);
intent.putExtra("scaleUpIfNeeded", true);
intent.putExtra(MediaStore.EXTRA_OUTPUT, getCustomImageExternalUri());
intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString());
startActivityForResult(intent, REQUEST_PICK_WALLPAPER);
return true;
} else if (preference == mUseContact) {
value = mUseContact.isChecked();
} else if (preference == mShowAvatar) {
value = mShowAvatar.isChecked();
} else if (preference == mBubbleFillParent) {
value = mShowAvatar.isChecked();
}
return super.onPreferenceTreeClick(preferenceScreen, preference);
}
private void restoreThemeMessageListDefaultPreferences() {
PreferenceManager.getDefaultSharedPreferences(this).edit().clear().apply();
setPreferenceScreen(null);
loadThemePrefs();
}
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.clear();
menu.add(R.menu.themes_message_list);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case THEMES_RESTORE_DEFAULTS:
restoreThemeMessageListDefaultPreferences();
return true;
case R.id.custom_image_delete:
deleteCustomImage();
return true;
case android.R.id.home:
// The user clicked on the Messaging icon in the action bar. Take them back from
// wherever they came from
finish();
return true;
}
return false;
}
private void deleteCustomImage() {
mContext.deleteFile(CUSTOM_IMAGE);
}
private Uri getCustomImageExternalUri() {
File dir = mContext.getExternalCacheDir();
File wallpaper = new File(dir, CUSTOM_IMAGE);
return Uri.fromFile(wallpaper);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == REQUEST_PICK_WALLPAPER) {
FileOutputStream wallpaperStream = null;
try {
wallpaperStream = mContext.openFileOutput(CUSTOM_IMAGE,
Context.MODE_WORLD_READABLE);
} catch (FileNotFoundException e) {
return; // NOOOOO
}
Uri selectedImageUri = getCustomImageExternalUri();
Bitmap bitmap = BitmapFactory.decodeFile(selectedImageUri.getPath());
bitmap.compress(Bitmap.CompressFormat.PNG, 100, wallpaperStream);
}
}
}
public void copy(File src, File dst) throws IOException {
InputStream in = new FileInputStream(src);
FileOutputStream out = new FileOutputStream(dst);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
}

getActivity() does not exists in Activity class, so to get Context of your Activity, just use this instead:
mContext = this;
as Activity is a child (subclass) of Context
https://developer.android.com/reference/android/app/Activity

PreferenceActivity doesn't have a getActivity method because it IS an Activity. Just assign your context like so: mContext = this;
getActivity() is a method of the Fragment class.
Also, unless you're trying to reference mContext outside of this class, you can ditch it all together and just use this instead.

Try this :-
Right click on project >properties > java build path > click on Libraries Tab >Click on add Library Button > select Jre System Library >Next > Finish >ok

Related

On broadcast receiver, check for write permission android M

I use broadcastreceiver of media folder android.hardware.action.NEW_PICTURE service to rename and move image using this code and it was running:
CameraReciver
package perim.ebrahimi.ir.perim;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
public class CameraReciver extends BroadcastReceiver {
private States states;
private SessionManager session;
private WriteService main;
#Override
public void onReceive(Context context, Intent intent) {
getStates(context);
if(states.getAPP()){
Cursor cursor = context.getContentResolver().query(intent.getData(), null, null, null, null);
cursor.moveToFirst();
if(cursor!=null){
String image_path = cursor.getString(cursor.getColumnIndex("_data"));
main = new WriteService();
main.writeFolder(image_path, states, context);
}
cursor.close();
} else abortBroadcast();
}
// OK
private void getStates(Context context){
session = new SessionManager(context.getApplicationContext());
states = new States();
states = session.getSession();
}
}
and here is WriteService:
package perim.ebrahimi.ir.perim;
import android.app.Activity;
import android.app.Application;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.widget.Toast;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class WriteService extends Activity {
private States states;
private Context context;
private static CalendarJalalian cal;
private static int day ;
private static int month ;
private static int year ;
private static int saat ;
private static int minut ;
private static int secnd ;
private int orientation = -1;
private static final int REQUEST_EXTERNAL_STORAGE = 100;
private static final int REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS=200;
private boolean mExternalStorageAvailable = false;
private boolean mExternalStorageWriteable = false;
// #Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// //setContentView(R.layout.activity_main);
//
// // A simple check of whether runtime permissions need to be managed
// if (Build.VERSION.SDK_INT >= 23) {
// checkMultiplePermissions();
// }
// }
public void writeFolder(String image_path, States _states, Context _context){
states = _states;
context= _context;
cal = new CalendarJalalian();
long fileSize = new File(image_path).length();
Cursor mediaCursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String[] {MediaStore.Images.ImageColumns.ORIENTATION,
MediaStore.MediaColumns.SIZE },
MediaStore.MediaColumns.DATE_ADDED + ">=?",
new String[]{String.valueOf(cal.getTimeInMillis()/1000 - 1)},
MediaStore.MediaColumns.DATE_ADDED + " desc");
if (mediaCursor != null && mediaCursor.getCount() !=0 ) {
while(mediaCursor.moveToNext()){
long size = mediaCursor.getLong(1);
if(size == fileSize){
orientation = mediaCursor.getInt(0);
break;
}
}
}
orientation = (orientation<0)?0:orientation;
image_path = changeName(image_path);
if(image_path.length()==0) return;
String image_jadid = copyFile(image_path);
if(states.getMain() && image_jadid.length()>0){
removeMain(image_path);
removeMedia(context, new File(image_path));
}
if(states.getPayam()) Toast.makeText(this, getText(R.string.imageSaved)+": "+states.getKhas(), 500).show();
}
private void checkExternalStorage(){
String[] aaa = new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE};
ActivityCompat.requestPermissions(this, aaa , REQUEST_EXTERNAL_STORAGE);
if(ContextCompat.checkSelfPermission(context, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_EXTERNAL_STORAGE);
} else {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
}
}
private static void removeMedia(Context context, File f) {
ContentResolver resolver = context.getContentResolver();
resolver.delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, MediaStore.Images.Media.DATA + "=?", new String[] { f.getAbsolutePath() });
}
// OK
private String changeName(String image_path){
String result = "";
day = cal.getDay();
month = cal.getMonth();
year = cal.getYear();
saat = Integer.parseInt(cal.getHHour());
minut = Integer.parseInt(cal.getMinute());
secnd = Integer.parseInt(cal.getSecond());
String persianDateName = String.format("%1$s_%2$s_%3$s__%4$s_%5$s_%6$s.jpg",
year,
((month<10)?"0"+month:month),
((day<10)?"0"+day:day),
((saat<10)?"0"+saat:saat),
((minut<10)?"0"+minut:minut),
((secnd<10)?"0"+secnd:secnd));
File from = new File(image_path);
if(from.exists()){
if(states.getOnimage()){
addTextToImage(image_path, persianDateName);
}
File to = new File(from.getParentFile(),persianDateName);
try
{
boolean b = from.renameTo(to);
if (!b) {
copy(from, to);
from.delete();
}
removeMedia(context, from);
sendToMedia(to, persianDateName);
result = to.getAbsolutePath();
}
catch(Exception ex){
ex.printStackTrace();
}
}
return result;
}
private void addTextToImage(String from, String persianDateName) {
Log.i("info","Draw "+persianDateName+" on image");
try
{
Log.i("info","1");
FileOutputStream fos = new FileOutputStream(from);
if(fos==null) Log.i("info","fos = null");
Log.i("info","2 = "+from);
Bitmap bitmap = BitmapFactory.decodeFile(from);
if(bitmap==null) Log.i("info","bitmap = null");
// Log.i("info","3");
android.graphics.Bitmap.Config bitmapConfig = bitmap.getConfig();
if(bitmapConfig==null) Log.i("info","bitmapConfig = null");
// Log.i("info","4");
// if (bitmapConfig == null) {
// bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
// }
Log.i("info","5");
bitmap = bitmap.copy(bitmapConfig, true);
Log.i("info","6");
Canvas canvas = new Canvas(bitmap);
Log.i("info","7");
Resources resources = this.getResources();
float scale = resources.getDisplayMetrics().density;
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.rgb(61, 61, 61));
paint.setTextSize((int) (14 * scale));
paint.setShadowLayer(1f, 0f, 1f, Color.WHITE);
Rect qab = new Rect();
paint.getTextBounds(persianDateName, 0, persianDateName.length(), qab);
int x = (bitmap.getWidth() - qab.width()) / 2;
int y = (bitmap.getHeight() + qab.height()) / 2;
canvas.drawText(persianDateName, x, y, paint);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
}
catch (IOException e)
{
e.printStackTrace();
}
Log.i("info","Text added on image");
}
private void copy(final File f1, final File f2) throws IOException {
if(f2.exists()) f2.delete();
//checkExternalStorage();
checkMultiplePermissions();
if(mExternalStorageAvailable && mExternalStorageWriteable) {
f2.createNewFile();
final RandomAccessFile file1 = new RandomAccessFile(f1, "r");
final RandomAccessFile file2 = new RandomAccessFile(f2, "rw");
file2.getChannel().write(file1.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, f1.length()));
file1.close();
file2.close();
}
}
private boolean canRename(final File f1, final File f2) {
final String p1 = f1.getAbsolutePath().replaceAll("^(/mnt/|/)", "");
final String p2 = f2.getAbsolutePath().replaceAll("^(/mnt/|/)", "");
return p1.replaceAll("\\/\\w+", "").equals(p2.replaceAll("\\/\\w+", ""));
}
// OK
private void removeMain(String image_path){
File f = new File(image_path);
if(f.exists()) f.delete();
}
// OK
private File createFileName(){
day = cal.getDay();
month = cal.getMonth();
year = cal.getYear();
saat = Integer.parseInt(cal.getHHour());
minut = Integer.parseInt(cal.getMinute());
secnd = Integer.parseInt(cal.getSecond());
String persianDateName = String.format("%1$s_%2$s_%3$s__%4$s_%5$s_%6$s.jpg",
year,
((month<10)?"0"+month:month),
((day<10)?"0"+day:day),
((saat<10)?"0"+saat:saat),
((minut<10)?"0"+minut:minut),
((secnd<10)?"0"+secnd:secnd));
String masirFolder = "";
if(states.getSal()) masirFolder += year;
if(states.getMah()) masirFolder += File.separator+ year+"_"+((month<10)?"0"+month:month);
if(states.getRuz()) masirFolder += File.separator+ year+"_"+((month<10)?"0"+month:month)+"_"+((day<10)?"0"+day:day);
if(states.getSaat()) masirFolder += File.separator+ year+"_"+((month<10)?"0"+month:month)+"_"+((day<10)?"0"+day:day)+"_"+((saat<10)?"0"+saat:saat);
if(states.getMinut()) masirFolder += File.separator+ year+"_"+((month<10)?"0"+month:month)+"_"+((day<10)?"0"+day:day)+"_"+((saat<10)?"0"+saat:saat)+"_"+((minut<10)?"0"+minut:minut);
if(states.getKhas().length()>0) masirFolder += File.separator+states.getKhas();
File directTime = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), masirFolder);
if (!directTime.mkdir()) makeDir(directTime);
directTime = new File(directTime, persianDateName);
return directTime;
}
// OK
private void makeDir(File direct){
direct.mkdirs();
}
// OK
private String copyFile(String image_path){
String masir = "";
File sourceFile = new File(image_path);
if (!sourceFile.exists()) {return masir;}
File destinationFile = createFileName();
FileChannel source = null;
FileChannel destination = null;
try {
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destinationFile).getChannel();
if (destination != null && source != null) {
destination.transferFrom(source, 0, source.size());
}
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
masir = destinationFile.getName();
sendToMedia(destinationFile, masir);
masir = destinationFile.getAbsolutePath();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return masir;
}
// OK
private void sendToMedia(File imageFile, String imageTitle){
ContentValues image = new ContentValues();
Date dateTaken = new Date();
File parent = imageFile.getParentFile();
String path = parent.toString().toLowerCase();
String name = parent.getName().toLowerCase();
image.put(MediaStore.Images.Media.TITLE, imageTitle);
image.put(MediaStore.Images.Media.DISPLAY_NAME, String.format(this.getText(R.string.imageDisplayName).toString(),states.getKhas()));
image.put(MediaStore.Images.Media.DESCRIPTION, String.format(this.getText(R.string.imageDescription).toString(),name));
image.put(MediaStore.Images.Media.DATE_ADDED, dateTaken.toString());
image.put(MediaStore.Images.Media.DATE_TAKEN, dateTaken.toString());
image.put(MediaStore.Images.Media.DATE_MODIFIED, dateTaken.toString());
image.put(MediaStore.Images.Media.MIME_TYPE, "image/png");
image.put(MediaStore.Images.Media.ORIENTATION, orientation);//getImageOrientation(imageFile.getAbsolutePath()));
image.put(MediaStore.Images.ImageColumns.BUCKET_ID, path.hashCode());
image.put(MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME, name);
image.put(MediaStore.Images.Media.SIZE, imageFile.length());
image.put(MediaStore.Images.Media.DATA, imageFile.getAbsolutePath());
this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, image);
}
private void checkMultiplePermissions() {
if (Build.VERSION.SDK_INT >= 23) {
List<String> permissionsNeeded = new ArrayList<String>();
List<String> permissionsList = new ArrayList<String>();
if (!addPermission(permissionsList, android.Manifest.permission.ACCESS_FINE_LOCATION)) {
permissionsNeeded.add("GPS");
}
if (!addPermission(permissionsList, android.Manifest.permission.READ_EXTERNAL_STORAGE)) {
permissionsNeeded.add("Read Storage");
}
if (permissionsList.size() > 0) {
requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
return;
}
}
}
private boolean addPermission(List<String> permissionsList, String permission) {
try {
if (Build.VERSION.SDK_INT >= 23)
if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
permissionsList.add(permission);
if (!shouldShowRequestPermissionRationale(permission))
return false;
}
} catch(Exception ex){
ex.printStackTrace();
}
return true;
}
}
But class addPermission raise error:
java.lang.NullPointerException: Attempt to invoke virtual method 'int
android.content.Context.checkSelfPermission(java.lang.String)' on a
null object reference
I think the way I call activity is not correct, but I have no idea how to do it, please help.
Edit:
I have found this difference in returned path:
String image_path = cursor.getString(cursor.getColumnIndex("_data"));
The changed part is obvious:
old but correct path: /storage/emulated/0/DCIM/Camera/IMG_20161215_173334.jpg
new but incorrect path: /storage/3466-033/DCIM/Camera/IMG_20161215_173334.jpg
I think since new devices permit user to select where to save Images, then returning address is changed accordingly.
How to get correct address out of cursor?
You can't do that with a broadcast receiver. You can check if you have a permission via ContextCompat.checkSelfPermission, but in order to request the permission, you need to call ActivityCompat.requestPermissions. It needs an activity, and the result will also arrive to that activity.
Given that, the best solution for you is to implement some activity which will explain the user what is going on and request the permission. If the broadcast receiver detects that it doesn't have the necessary permission, it would launch this activity. When the permission is granted, the normal operation would be resumed.
I have to say that as a user it would be very weird to me if a dialog with a permission request suddenly popped up out of the blue, so I think it's for the best that you need to have an activity to request permissions.
Judging by your path, however, it is definitely somewhere on the SD card. This means that the SD card write restrictions apply. That means that requesting permissions for writing won't help. Take a look at this question: How to avoid the “EACCES permission denied” on SD card?

Call a photo intent

I am having a problem when I try to call the Camera Intent and make it return the URI of the photo i took and save it in the Sqlite database.
I always get the following log:
06-06 13:06:35.195 19091-19091/com.example.eduardo.voiceblog_beta >E/AndroidRuntime﹕ FATAL EXCEPTION: main Process: com.example.eduardo.voiceblog_beta, PID: 19091 java.lang.NullPointerException: file
at android.net.Uri.fromFile(Uri.java:447)
at camera.Util.getOutputMediaFileUri(Util.java:21)
at >com.example.eduardo.voiceblog_beta.ConfirmaFoto$1.onClick(ConfirmaFoto.ja>va:64)
at android.view.View.performClick(View.java:4761)
at android.view.View$PerformClick.run(View.java:19767)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5312)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at >com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.jav>a:901)
at >com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
Here is my Util class:
package camera;
import android.net.Uri;
import android.os.Environment;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Created by eduardo on 31/05/15.
* Classe onde defino caminho onde as fotos serão armazenadas
*/
public class Util {
public static final int TIPO_IMAGEM = 1;
public static String localFoto;
public static Uri getOutputMediaFileUri (int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/*public static Uri getOutputMediaFileUri (int type) {
return Uri.fromFile(getOutputMediaFile(type));
}*/
public static File getOutputMediaFile (int type){
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "TesteCamera");
if (! mediaStorageDir.exists()) {
if (! mediaStorageDir.mkdirs()) {
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == TIPO_IMAGEM) {
localFoto = mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg";
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
}
Here is the class where i call the photo Intent:
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.provider.MediaStore;
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 java.text.SimpleDateFormat;
import java.util.Date;
import BD.Postagem;
import BD.PostagemDAO;
import camera.Util;
public class ConfirmaFoto extends ActionBarActivity {
Button btnProximo;
private PostagemDAO bd;
private static final int TIPO_IMAGEM = 1;
String uriFoto;
private Uri fileUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_confirma_foto);
btnProximo = (Button) findViewById(R.id.btnConfirmaFoto);
btnProximo.setOnClickListener(proximo);
bd = new PostagemDAO(this);
bd.abrir();
}
View.OnClickListener proximo = new View.OnClickListener() {
public void onClick(View v) {
Intent principal = new Intent(ConfirmaFoto.this, MainActivity.class);
String tit = getIntent().getExtras().getString("titulo",null);
String com = getIntent().getExtras().getString("comentario",null);
Postagem postagem = new Postagem();
postagem.setTituloPostagem(tit);
postagem.setComentarioPostagem(com);
Date dataAtual = new Date();
SimpleDateFormat formataData = new SimpleDateFormat("dd/MM/yyyy");
String data = formataData.format(dataAtual);
postagem.setDataPostagem(data);
postagem.setExtra("FIXO");
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = Util.getOutputMediaFileUri(Util.TIPO_IMAGEM);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, 1);
postagem.setCaminhoFoto(uriFoto);
bd.criarPostagem(postagem);
bd.fechar();
startActivity(principal);
}
};
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
uriFoto = Util.getOutputMediaFileUri(Util.TIPO_IMAGEM).toString();
/*Bitmap vt = BitmapFactory.decodeFile(Util.localFoto);
vt = Bitmap.createScaledBitmap(vt, 480, 600, false);
Matrix matrix = new Matrix();
matrix.postRotate(90);
Bitmap resizedBitmap = Bitmap.createBitmap(vt, 0, 0, 480, 600,matrix, true);
img.setImageBitmap(resizedBitmap);*/
} else if (resultCode == RESULT_CANCELED) {
} else {
}
}
}
#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_confirma_foto, 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 think the problem is here:
if (! mediaStorageDir.exists()) {
if (! mediaStorageDir.mkdirs()) {
return null;
}
}
you need to add this the permission to the manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

How to slide images from arrayList in android

I am having an arrayList of Imageurls and want to slide it one by one when user slides image second image should dsplay,I have tried as belo but I only able to change when i touch,It changes on touch,But i want it on slide..So Please tell me what code changes should i make..Thank you
package com.epe.smaniquines.ui;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Timer;
import twitter4j.Twitter;
import twitter4j.auth.RequestToken;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.URLSpan;
import android.util.Base64;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterViewFlipper;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
import com.epe.smaniquines.R;
import com.epe.smaniquines.adapter.FlipperAdapter;
import com.epe.smaniquines.adapter.ImageSwipeAdapter;
import com.epe.smaniquines.adapter.SimpleGestureFilter;
import com.epe.smaniquines.backend.AlertDialogManager;
import com.epe.smaniquines.backend.ConnectionDetector;
import com.epe.smaniquines.uc.Menu;
import com.epe.smaniquines.util.Const;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
public class DetailsActivity extends Activity implements OnClickListener,
OnTouchListener {
private SimpleGestureFilter detector;
ImageView proImage, ivSave, ivInfo, ivPlay, ivBak, iv_share;
RelativeLayout rl_botm, rl_option;
TextView tv_facebuk, tv_twiter, tv_nothanks, tv_email, tv_save, tv_quote;
String big_img;
int pos;
ViewPager viewPager;
ImageSwipeAdapter adapter;
private static SharedPreferences mSharedPreferences;
ArrayList<String> resultArray;
private DisplayImageOptions options;
public static ImageLoader imageLoader;
RelativeLayout rl_info;
public boolean flag = false;
Menu menu;
public boolean flag1 = false;
boolean isOnClick = false;
int i = 0;
String cat_nem;
File casted_image;
private int PicPosition;
private Handler handler = new Handler();
ProgressDialog pDialog;
ConnectionDetector cd;
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
int mFlipping = 0;
ViewFlipper viewFlipper;
Timer timer;
int flagD = 0;
String data;
String shareType;
File image;
static String PREFERENCE_NAME = "twitter_oauth";
static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";
TextView titledetail;
static final String TWITTER_CALLBACK_URL = "oauth://t4jsample";
// Twitter oauth urls
static final String URL_TWITTER_AUTH = "auth_url";
static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";
public static String PACKAGE_NAME;
static String TWITTER_CONSUMER_KEY = "AzFSBq1Od4lYGGcGR0u9GkMIT"; // place
static String TWITTER_CONSUMER_SECRET = "MBwdard2Y4l6LT6z219NJ6x8aZ4jyK8JBKZ85usRPcDP8ujwM0"; // place
Matrix matrix = new Matrix();
Matrix savedMatrix = new Matrix();
static final int NONE = 0;
static final int DRAG = 1;
static final int ZOOM = 2;
int mode = NONE;
// Remember some things for zooming
PointF start = new PointF();
PointF mid = new PointF();
float oldDist = 1f;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_detail);
PACKAGE_NAME = getApplicationContext().getPackageName();
initialize();
cat_nem = getIntent().getStringExtra("cat_name");
System.out.println(":::::::::::CAt nem:::::::::" + cat_nem);
titledetail.setText(cat_nem);
proImage.setScaleType(ImageView.ScaleType.FIT_CENTER);
proImage.setOnTouchListener(this);
showHashKey(this);
printKeyHashForThisDevice();
pos = getIntent().getIntExtra("pos", 0);
cd = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(DetailsActivity.this,
"Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
// Check if twitter keys are set
if (TWITTER_CONSUMER_KEY.trim().length() == 0
|| TWITTER_CONSUMER_SECRET.trim().length() == 0) {
// Internet Connection is not present
alert.showAlertDialog(DetailsActivity.this, "Twitter oAuth tokens",
"Please set your twitter oauth tokens first!", false);
// stop executing code by return
return;
}
mSharedPreferences = getApplicationContext().getSharedPreferences(
"MyPref", 0);
/*
* Intent i = getIntent(); data = i.getStringExtra("data"); shareType =
* i.getStringExtra("type");
*/
big_img = getIntent().getStringExtra(Const.TAG_BIG_IMG);
// imageLoader.displayImage(big_img, proImage, options);
resultArray = getIntent().getStringArrayListExtra("array");
viewPager = (ViewPager) findViewById(R.id.view_pager);
viewPager.setVisibility(View.VISIBLE);
ImagePagerAdapter adapter = new ImagePagerAdapter();
viewPager.setCurrentItem(resultArray.indexOf(pos));
viewPager.setAdapter(adapter);
ivInfo.setOnClickListener(this);
ivPlay.setOnClickListener(this);
tv_email.setOnClickListener(this);
tv_facebuk.setOnClickListener(this);
tv_nothanks.setOnClickListener(this);
tv_save.setOnClickListener(this);
tv_twiter.setOnClickListener(this);
iv_share.setOnClickListener(this);
ivBak.setOnClickListener(this);
tv_quote.setOnClickListener(this);
proImage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
viewPager.setVisibility(View.VISIBLE);
}
});
// viewFlipper = (ViewFlipper) findViewById(R.id.flipper);
/*
* imageLoader.displayImage(big_img, proImage, options);
* proImage.postDelayed(swapImage, 1000);
*/
viewPager.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (isOnClick) {
if (event.getX() > viewPager.getWidth() / 2) {
// go to next
i = pos;
viewPager.setCurrentItem(resultArray.indexOf(i),
true);
i++;
} else {
viewPager.setCurrentItem(resultArray.indexOf(i),
true);
i--;
// go to previous
}
return true;
}
}
return false;
}
});
}
public void open(View view) {
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("*/*");
shareIntent.putExtra(Intent.EXTRA_TEXT, "Hello test"); // <- String
Uri screenshotUri = Uri.parse(image.getPath());
shareIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
startActivity(Intent.createChooser(shareIntent, "Share image using"));
}
void initialize() {
proImage = (ImageView) findViewById(R.id.iv_det);
ivInfo = (ImageView) findViewById(R.id.iv_info);
ivPlay = (ImageView) findViewById(R.id.iv_play);
ivBak = (ImageView) findViewById(R.id.iv_back);
rl_botm = (RelativeLayout) findViewById(R.id.rl_bottom);
rl_option = (RelativeLayout) findViewById(R.id.rl_options);
tv_save = (TextView) findViewById(R.id.tv_save);
tv_email = (TextView) findViewById(R.id.tv_email);
tv_facebuk = (TextView) findViewById(R.id.tv_facebook);
tv_nothanks = (TextView) findViewById(R.id.tv_no_thanks);
tv_twiter = (TextView) findViewById(R.id.tv_twiter);
rl_option.setVisibility(View.GONE);
tv_quote = (TextView) findViewById(R.id.tv_qote);
iv_share = (ImageView) findViewById(R.id.iv_share);
imageLoader = ImageLoader.getInstance();
imageLoader.init(ImageLoaderConfiguration
.createDefault(DetailsActivity.this));
rl_info = (RelativeLayout) findViewById(R.id.rl_info);
rl_info.setVisibility(View.GONE);
resultArray = new ArrayList<String>();
ivPlay.setVisibility(View.VISIBLE);
titledetail = (TextView) findViewById(R.id.titledetail);
// twitter
// Login button
}
#SuppressLint("NewApi")
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.iv_share:
rl_option.setVisibility(View.VISIBLE);
rl_info.setVisibility(View.GONE);
if (flag1) {
rl_option.setVisibility(View.VISIBLE);
flag1 = false;
} else {
rl_option.setVisibility(View.GONE);
flag1 = true;
}
break;
case R.id.iv_play:
proImage.setVisibility(View.GONE);
AdapterViewFlipper flipper = (AdapterViewFlipper) findViewById(R.id.flipper);
flipper.setAutoStart(true);
flipper.setAdapter(new FlipperAdapter(DetailsActivity.this,
resultArray));
Animation in = AnimationUtils.loadAnimation(this,
android.R.anim.slide_in_left);
Animation out = AnimationUtils.loadAnimation(this,
android.R.anim.slide_out_right);
flipper.setAnimation(out);
ivPlay.setVisibility(View.INVISIBLE);
break;
case R.id.iv_back:
finish();
break;
case R.id.tv_email:
rl_option.setVisibility(View.GONE);
Intent email = new Intent(Intent.ACTION_SEND);
email.putExtra(Intent.EXTRA_EMAIL,
new String[] { "youremail#yahoo.com" });
email.putExtra(Intent.EXTRA_SUBJECT, "subject");
email.putExtra(Intent.EXTRA_TEXT, "message");
email.setType("message/rfc822");
startActivity(Intent.createChooser(email,
"Choose an Email client :"));
break;
case R.id.tv_save:
save();
rl_option.setVisibility(View.GONE);
break;
case R.id.tv_facebook:
// facebookShare();
/*
* save(); open(v);
*/
rl_option.setVisibility(View.GONE);
break;
case R.id.tv_no_thanks:
rl_option.setVisibility(View.GONE);
break;
case R.id.tv_twiter:
rl_option.setVisibility(View.GONE);
// loginToTwitter();
// new updateTwitterStatus().execute("3sManiquines");
break;
case R.id.iv_info:
rl_info.setVisibility(View.VISIBLE);
rl_option.setVisibility(View.GONE);
if (flag) {
rl_info.setVisibility(View.VISIBLE);
flag = false;
} else {
rl_info.setVisibility(View.GONE);
flag = true;
}
break;
case R.id.tv_qote:
rl_option.setVisibility(View.GONE);
String url = big_img;
SpannableStringBuilder builder = new SpannableStringBuilder();
builder.append("Hi Go to product for details:");
int start = builder.length();
builder.append(url);
int end = builder.length();
builder.setSpan(new URLSpan(url), start, end,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL, new String[] { "" });
i.putExtra(Intent.EXTRA_SUBJECT, "Quote");
i.putExtra(Intent.EXTRA_TEXT, builder);
startActivity(Intent.createChooser(i, "Select application"));
break;
}
}
public static void showHashKey(Context context) {
try {
PackageInfo info = context.getPackageManager().getPackageInfo(
"com.epe.3SManiquines", PackageManager.GET_SIGNATURES); // Your
// package
// name
// here
for (android.content.pm.Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.v("KeyHash:",
Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
}
// slide show..!!!
MediaPlayer introSound, bellSound;
Runnable swapImage = new Runnable() {
#Override
public void run() {
myslideshow();
handler.postDelayed(this, 1000);
}
};
private void myslideshow() {
PicPosition = resultArray.indexOf(big_img);
if (PicPosition >= resultArray.size())
PicPosition = resultArray.indexOf(big_img); // stop
else
resultArray.get(PicPosition);// move to the next gallery element.
}
//
// SAVE TO SD CARD..!!
void save() {
BitmapDrawable drawable = (BitmapDrawable) proImage.getDrawable();
Bitmap bitmap = drawable.getBitmap();
File sdCardDirectory = Environment.getExternalStorageDirectory();
File dir = new File(sdCardDirectory.getAbsolutePath()
+ "/3sManiquines/");
image = new File(sdCardDirectory, "3s_" + System.currentTimeMillis()
+ ".png");
dir.mkdirs();
boolean success = false;
// Encode the file as a PNG image.
FileOutputStream outStream;
try {
outStream = new FileOutputStream(image);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
/* 100 to keep full quality of the image */
outStream.flush();
outStream.close();
success = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (success) {
addImageToGallery(dir + "", DetailsActivity.this);
Toast.makeText(getApplicationContext(), "Image saved with success",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Error during image saving", Toast.LENGTH_LONG).show();
}
}//
public static void addImageToGallery(final String filePath,
final Context context) {
ContentValues values = new ContentValues();
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(Images.Media.MIME_TYPE, "image/png");
values.put(MediaStore.MediaColumns.DATA, filePath);
context.getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI,
values);
}
// facebook...
private void printKeyHashForThisDevice() {
try {
System.out
.println("::::::::::::::::::::HAsh key called:::::::::::::");
PackageInfo info = getPackageManager().getPackageInfo(PACKAGE_NAME,
PackageManager.GET_SIGNATURES);
for (android.content.pm.Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
String keyHash = Base64.encodeToString(md.digest(),
Base64.DEFAULT);
System.out
.println(":::::::::::KEy hash:::::::::::::" + keyHash);
System.out.println("================KeyHash================ "
+ keyHash);
}
} catch (NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
}
#Override
public boolean onTouch(View v, MotionEvent event) {
float touchPointX = event.getX();
float touchPointY = event.getY();
int[] coordinates = new int[2];
rl_info.getLocationOnScreen(coordinates);
rl_option.getLocationOnScreen(coordinates);
if (touchPointX < coordinates[0]
|| touchPointX > coordinates[0] + rl_info.getWidth()
|| touchPointY < coordinates[1]
|| touchPointY > coordinates[1] + rl_info.getHeight())
rl_info.setVisibility(View.INVISIBLE);
rl_option.setVisibility(View.INVISIBLE);
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN: // first finger down only
break;
case MotionEvent.ACTION_UP: // first finger lifted
/*
* if (i < resultArray.size()) {
* imageLoader.displayImage(resultArray.get(i), proImage); i++; }
*/
case MotionEvent.ACTION_POINTER_UP: // second finger lifted
break;
case MotionEvent.ACTION_POINTER_DOWN: // second finger down
break;
case MotionEvent.ACTION_MOVE:
break;
}
return true;
}
//
private class ImagePagerAdapter extends PagerAdapter {
#Override
public int getCount() {
return resultArray.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = DetailsActivity.this;
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(
R.dimen.padding_medium);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageLoader.displayImage(resultArray.get(position), proImage);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
}
If you don't want the way ViewPager slide and handles pages , then you have to implement you own view ( Not with ViewPager ).
ViewPager by default slides through the pages on swipe.
If you want to slide on clicking left or right side to the viewpager , then on touch ACTION_UP call
viewPager.setCurrentItem( PAGE_NUM , true );
This will slide to next or previous page and load appropriate image url.
You can use ViewPager with fragments for each image url.
This way the memory used to draw image will be handled well by viewpager...
More the image reference you keep in memory , more the possibility of the app crashing.

Sliding after auto slide on button clicke using ViewPager gives erro in android

I have made a View Pager in that I want to implement manually slide(OnTOuch) and auto slide(onButton Click)..Both functions are working when use alone.But when i slede from one to another image and start auto Slide,It gives me IllegalStateException..And stops..Please help me to solve it,My code is as below:
package com.epe.smaniquines.ui;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Timer;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.URLSpan;
import android.util.Base64;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
import com.epe.smaniquines.R;
import com.epe.smaniquines.adapter.SimpleGestureFilter;
import com.epe.smaniquines.backend.AlertDialogManager;
import com.epe.smaniquines.backend.ConnectionDetector;
import com.epe.smaniquines.uc.Menu;
import com.epe.smaniquines.util.Const;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
public class DetailsActivity extends Activity implements OnClickListener,
OnTouchListener {
private SimpleGestureFilter detector;
ImageView proImage, ivSave, ivInfo, ivPlay, ivBak, iv_share;
RelativeLayout rl_botm, rl_option;
TextView tv_facebuk, tv_twiter, tv_nothanks, tv_email, tv_save, tv_quote;
String big_img;
int pos;
ImagePagerAdapter adapter;
ViewPager viewPager;
private static SharedPreferences mSharedPreferences;
ArrayList<String> resultArray;
private DisplayImageOptions options;
public static ImageLoader imageLoader;
RelativeLayout rl_info;
public boolean flag = false;
Menu menu;
public boolean flag1 = false;
boolean isOnClick = false;
int i = 0;
String cat_nem;
File casted_image;
private int PicPosition;
private Handler handler = new Handler();
ProgressDialog pDialog;
ConnectionDetector cd;
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
int mFlipping = 0;
ViewFlipper viewFlipper;
Timer timer;
int flagD = 0;
String data;
String shareType;
File image;
static String PREFERENCE_NAME = "twitter_oauth";
static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";
TextView titledetail;
static final String TWITTER_CALLBACK_URL = "oauth://t4jsample";
// Twitter oauth urls
static final String URL_TWITTER_AUTH = "auth_url";
static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";
public static String PACKAGE_NAME;
static String TWITTER_CONSUMER_KEY = "AzFSBq1Od4lYGGcGR0u9GkMIT"; // place
static String TWITTER_CONSUMER_SECRET = "MBwdard2Y4l6LT6z219NJ6x8aZ4jyK8JBKZ85usRPcDP8ujwM0"; // place
Matrix matrix = new Matrix();
Matrix savedMatrix = new Matrix();
static final int NONE = 0;
static final int DRAG = 1;
static final int ZOOM = 2;
int mode = NONE;
// Remember some things for zooming
PointF start = new PointF();
PointF mid = new PointF();
float oldDist = 1f;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_detail);
PACKAGE_NAME = getApplicationContext().getPackageName();
initialize();
cat_nem = getIntent().getStringExtra("cat_name");
System.out.println(":::::::::::CAt nem:::::::::" + cat_nem);
titledetail.setText(cat_nem);
proImage.setScaleType(ImageView.ScaleType.FIT_CENTER);
proImage.setOnTouchListener(this);
showHashKey(this);
printKeyHashForThisDevice();
pos = getIntent().getIntExtra("pos", 0);
System.out.println(":::::::::::::::current pos::::::::::" + pos);
cd = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(DetailsActivity.this,
"Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
// Check if twitter keys are set
if (TWITTER_CONSUMER_KEY.trim().length() == 0
|| TWITTER_CONSUMER_SECRET.trim().length() == 0) {
// Internet Connection is not present
alert.showAlertDialog(DetailsActivity.this, "Twitter oAuth tokens",
"Please set your twitter oauth tokens first!", false);
// stop executing code by return
return;
}
mSharedPreferences = getApplicationContext().getSharedPreferences(
"MyPref", 0);
/*
* Intent i = getIntent(); data = i.getStringExtra("data"); shareType =
* i.getStringExtra("type");
*/
big_img = getIntent().getStringExtra(Const.TAG_BIG_IMG);
// imageLoader.displayImage(big_img, proImage, options);
resultArray = getIntent().getStringArrayListExtra("array");
viewPager = (ViewPager) findViewById(R.id.view_pager);
viewPager.setVisibility(View.VISIBLE);
adapter = new ImagePagerAdapter();
viewPager.setCurrentItem(resultArray.indexOf(pos));
viewPager.setAdapter(adapter);
ivInfo.setOnClickListener(this);
ivPlay.setOnClickListener(this);
tv_email.setOnClickListener(this);
tv_facebuk.setOnClickListener(this);
tv_nothanks.setOnClickListener(this);
tv_save.setOnClickListener(this);
tv_twiter.setOnClickListener(this);
iv_share.setOnClickListener(this);
ivBak.setOnClickListener(this);
tv_quote.setOnClickListener(this);
proImage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
viewPager.setVisibility(View.VISIBLE);
Animation anim;
anim = (Animation) getResources().getAnimation(
R.anim.animated_activity_slide_right_in);
viewPager.setAnimation(anim);
}
});
// viewFlipper = (ViewFlipper) findViewById(R.id.flipper);
/*
* imageLoader.displayImage(big_img, proImage, options);
* proImage.postDelayed(swapImage, 1000);
*/
viewPager.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
if (isOnClick) {
if (event.getX() > viewPager.getWidth() / 2) {
// go to next
viewPager.setCurrentItem(resultArray.indexOf(i),
true);
i++;
} else {
viewPager.setCurrentItem(resultArray.indexOf(i),
true);
i--;
// go to previous
}
return true;
}
}
return false;
}
});
}
public void open(View view) {
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("*/*");
shareIntent.putExtra(Intent.EXTRA_TEXT, "Hello test"); // <- String
Uri screenshotUri = Uri.parse(image.getPath());
shareIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
startActivity(Intent.createChooser(shareIntent, "Share image using"));
}
void initialize() {
proImage = (ImageView) findViewById(R.id.iv_det);
ivInfo = (ImageView) findViewById(R.id.iv_info);
ivPlay = (ImageView) findViewById(R.id.iv_play);
ivBak = (ImageView) findViewById(R.id.iv_back);
rl_botm = (RelativeLayout) findViewById(R.id.rl_bottom);
rl_option = (RelativeLayout) findViewById(R.id.rl_options);
tv_save = (TextView) findViewById(R.id.tv_save);
tv_email = (TextView) findViewById(R.id.tv_email);
tv_facebuk = (TextView) findViewById(R.id.tv_facebook);
tv_nothanks = (TextView) findViewById(R.id.tv_no_thanks);
tv_twiter = (TextView) findViewById(R.id.tv_twiter);
rl_option.setVisibility(View.GONE);
tv_quote = (TextView) findViewById(R.id.tv_qote);
iv_share = (ImageView) findViewById(R.id.iv_share);
imageLoader = ImageLoader.getInstance();
imageLoader.init(ImageLoaderConfiguration
.createDefault(DetailsActivity.this));
rl_info = (RelativeLayout) findViewById(R.id.rl_info);
rl_info.setVisibility(View.GONE);
resultArray = new ArrayList<String>();
ivPlay.setVisibility(View.VISIBLE);
titledetail = (TextView) findViewById(R.id.titledetail);
// twitter
// Login button
}
#SuppressLint("NewApi")
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.iv_share:
rl_option.setVisibility(View.VISIBLE);
rl_info.setVisibility(View.GONE);
if (flag1) {
rl_option.setVisibility(View.VISIBLE);
flag1 = false;
} else {
rl_option.setVisibility(View.GONE);
flag1 = true;
}
break;
case R.id.iv_play:
/*
* proImage.setVisibility(View.GONE);
*
* AdapterViewFlipper flipper = (AdapterViewFlipper)
* findViewById(R.id.flipper); flipper.setAutoStart(true);
* flipper.setAdapter(new FlipperAdapter(DetailsActivity.this,
* resultArray));
*/
i = 0;
final Handler handler = new Handler();
final Runnable ViewPagerVisibleScroll = new Runnable() {
#Override
public void run() {
if (i <= adapter.getCount() - 1) {
viewPager.setCurrentItem(i, true);
handler.postDelayed(this, 2000);
i++;
}
}
};
new Thread(ViewPagerVisibleScroll).start();
ivPlay.setVisibility(View.INVISIBLE);
break;
case R.id.iv_back:
finish();
break;
case R.id.tv_email:
rl_option.setVisibility(View.GONE);
Intent email = new Intent(Intent.ACTION_SEND);
email.putExtra(Intent.EXTRA_EMAIL,
new String[] { "youremail#yahoo.com" });
email.putExtra(Intent.EXTRA_SUBJECT, "subject");
email.putExtra(Intent.EXTRA_TEXT, "message");
email.setType("message/rfc822");
startActivity(Intent.createChooser(email,
"Choose an Email client :"));
break;
case R.id.tv_save:
save();
rl_option.setVisibility(View.GONE);
break;
case R.id.tv_facebook:
// facebookShare();
/*
* save(); open(v);
*/
rl_option.setVisibility(View.GONE);
break;
case R.id.tv_no_thanks:
rl_option.setVisibility(View.GONE);
break;
case R.id.tv_twiter:
rl_option.setVisibility(View.GONE);
// loginToTwitter();
// new updateTwitterStatus().execute("3sManiquines");
break;
case R.id.iv_info:
rl_info.setVisibility(View.VISIBLE);
rl_option.setVisibility(View.GONE);
if (flag) {
rl_info.setVisibility(View.VISIBLE);
flag = false;
} else {
rl_info.setVisibility(View.GONE);
flag = true;
}
break;
case R.id.tv_qote:
rl_option.setVisibility(View.GONE);
String url = big_img;
SpannableStringBuilder builder = new SpannableStringBuilder();
builder.append("Hi Go to product for details:");
int start = builder.length();
builder.append(url);
int end = builder.length();
builder.setSpan(new URLSpan(url), start, end,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL, new String[] { "" });
i.putExtra(Intent.EXTRA_SUBJECT, "Quote");
i.putExtra(Intent.EXTRA_TEXT, builder);
startActivity(Intent.createChooser(i, "Select application"));
break;
}
}
public static void showHashKey(Context context) {
try {
PackageInfo info = context.getPackageManager().getPackageInfo(
"com.epe.3SManiquines", PackageManager.GET_SIGNATURES); // Your
// package
// name
// here
for (android.content.pm.Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.v("KeyHash:",
Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
}
// slide show..!!!
MediaPlayer introSound, bellSound;
Runnable swapImage = new Runnable() {
#Override
public void run() {
myslideshow();
handler.postDelayed(this, 1000);
}
};
private void myslideshow() {
PicPosition = resultArray.indexOf(big_img);
if (PicPosition >= resultArray.size())
PicPosition = resultArray.indexOf(big_img); // stop
else
resultArray.get(PicPosition);// move to the next gallery element.
}
//
// SAVE TO SD CARD..!!
void save() {
BitmapDrawable drawable = (BitmapDrawable) proImage.getDrawable();
Bitmap bitmap = drawable.getBitmap();
File sdCardDirectory = Environment.getExternalStorageDirectory();
File dir = new File(sdCardDirectory.getAbsolutePath()
+ "/3sManiquines/");
image = new File(sdCardDirectory, "3s_" + System.currentTimeMillis()
+ ".png");
dir.mkdirs();
boolean success = false;
// Encode the file as a PNG image.
FileOutputStream outStream;
try {
outStream = new FileOutputStream(image);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
/* 100 to keep full quality of the image */
outStream.flush();
outStream.close();
success = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (success) {
addImageToGallery(dir + "", DetailsActivity.this);
Toast.makeText(getApplicationContext(), "Image saved with success",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Error during image saving", Toast.LENGTH_LONG).show();
}
}//
public static void addImageToGallery(final String filePath,
final Context context) {
ContentValues values = new ContentValues();
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(Images.Media.MIME_TYPE, "image/png");
values.put(MediaStore.MediaColumns.DATA, filePath);
context.getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI,
values);
}
// facebook...
private void printKeyHashForThisDevice() {
try {
System.out
.println("::::::::::::::::::::HAsh key called:::::::::::::");
PackageInfo info = getPackageManager().getPackageInfo(PACKAGE_NAME,
PackageManager.GET_SIGNATURES);
for (android.content.pm.Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
String keyHash = Base64.encodeToString(md.digest(),
Base64.DEFAULT);
System.out
.println(":::::::::::KEy hash:::::::::::::" + keyHash);
System.out.println("================KeyHash================ "
+ keyHash);
}
} catch (NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
}
#Override
public boolean onTouch(View v, MotionEvent event) {
float touchPointX = event.getX();
float touchPointY = event.getY();
int[] coordinates = new int[2];
rl_info.getLocationOnScreen(coordinates);
rl_option.getLocationOnScreen(coordinates);
if (touchPointX < coordinates[0]
|| touchPointX > coordinates[0] + rl_info.getWidth()
|| touchPointY < coordinates[1]
|| touchPointY > coordinates[1] + rl_info.getHeight())
rl_info.setVisibility(View.INVISIBLE);
rl_option.setVisibility(View.INVISIBLE);
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN: // first finger down only
break;
case MotionEvent.ACTION_UP: // first finger lifted
/*
* if (i < resultArray.size()) {
* imageLoader.displayImage(resultArray.get(i), proImage); i++; }
*/
case MotionEvent.ACTION_POINTER_UP: // second finger lifted
break;
case MotionEvent.ACTION_POINTER_DOWN: // second finger down
break;
case MotionEvent.ACTION_MOVE:
break;
}
return true;
}
//
private class ImagePagerAdapter extends PagerAdapter {
#Override
public int getCount() {
return resultArray.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = DetailsActivity.this;
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(
R.dimen.padding_medium);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageLoader.displayImage(resultArray.get(position), imageView);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
}
Try it and post output or logcat
private void postInitViewPager() {
try {
Class<?> viewpager = ViewPager.class;
Field scroller = viewpager.getDeclaredField("mScroller");
scroller.setAccessible(true);
Field interpolator = viewpager.getDeclaredField("sInterpolator");
interpolator.setAccessible(true);
mScroller = new ScrollerCustomDuration(getContext(),
(Interpolator) interpolator.get(null));
Log.d("TAG", "mScroller is: " + mScroller + ", "
+ mScroller.getClass().getSuperclass().getCanonicalName() + "; this class is "
+ this + ", " + getClass().getSuperclass().getCanonicalName());
scroller.set(this, mScroller);
} catch (Exception e) {
Log.e("MyPager", e.getMessage());
}

My barcode app force closes whenever it runs

I got my app to read an app and then tell me what the code says, but now I'm trying to have it encode the string back into a barcode and display it as an image on the screen. However, it always force closes the app before it starts. Here is my code, please help:
import java.util.EnumMap;
import java.util.Map;
import android.os.Bundle;
import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.view.Gravity;
import android.view.Menu;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
public class Main extends Activity {
IntentIntegrator integrator = new IntentIntegrator(this);
private static final int WHITE = 0xFFFFFFFF;
private static final int BLACK = 0xFF000000;
LinearLayout myLayout = (LinearLayout)findViewById(R.id.myLayout);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//LinearLayout myLayout = (LinearLayout)findViewById(R.id.myLayout);
Button btn =(Button)findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
integrator.initiateScan();
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanResult != null) {
Toast.makeText(Main.this,
"works",
Toast.LENGTH_SHORT).show();
String contents = intent.getStringExtra("SCAN_RESULT");
String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
Toast.makeText(Main.this,
contents,
Toast.LENGTH_SHORT).show();
Bitmap bitmap = null;
ImageView iv = new ImageView(this);
try {
bitmap = encodeAsBitmap(contents, BarcodeFormat.CODE_128, 600, 300);
iv.setImageBitmap(bitmap);
} catch (WriterException e) {
e.printStackTrace();
}
myLayout.addView(iv);
TextView tv = new TextView(this);
tv.setGravity(Gravity.CENTER_HORIZONTAL);
tv.setText(contents);
myLayout.addView(tv);
}
}
Bitmap encodeAsBitmap(String contents, BarcodeFormat format, int img_width, int img_height) throws WriterException {
String contentsToEncode = contents;
if (contentsToEncode == null) {
return null;
}
Map<EncodeHintType, Object> hints = null;
hints = new EnumMap<EncodeHintType, Object>(EncodeHintType.class);
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
MultiFormatWriter writer = new MultiFormatWriter();
BitMatrix result;
try {
result = writer.encode(contentsToEncode, format, img_width, img_height, hints);
} catch (IllegalArgumentException iae) {
// Unsupported format
return null;
}
int width = result.getWidth();
int height = result.getHeight();
int[] pixels = new int[width * height];
for (int y = 0; y < height; y++) {
int offset = y * width;
for (int x = 0; x < width; x++) {
pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
}
}
Bitmap bitmap = Bitmap.createBitmap(width, height,
Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
}
#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;
}
}
IntentResult and IntentIntegrator are both from ZXing.
Log Cat:
03-15 13:05:04.303: E/AndroidRuntime(4363): FATAL EXCEPTION: main
In your toast, instead of Main.this you should try getApplicationContext(). Also recall that an Activity is a type of Context.
Try to move this:
LinearLayout myLayout = (LinearLayout)findViewById(R.id.myLayout);
under:
setContentView(R.layout.main);

Categories

Resources