Im trying to build an RSS feed reader that needs to do some client side SSL authentication.
Ive got, or at least think i have, the certificate and now cannot figure out how to setup a ssl tunnel to send the certificate to the server to authenticate.
here is what i have so far:
public class Authenticator extends Activity {
PrivateKey privateKey = null;
String SavedAlias = "";
private static final String TAG = "AUTHENTICATOR.CLASS";
final HttpParams httpParams = new BasicHttpParams();
private KeyStore mKeyStore = KeyStore.getInstance();
public Handler mHandler = new Handler(Looper.getMainLooper());
public void run()
{
mHandler.post(new Runnable() {
public void run() {
new AliasLoader().execute();
}
});
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getCertificates("TEST");
}
public class AliasLoader extends AsyncTask<Void, Void, X509Certificate[]>
{
X509Certificate[] chain = null;
@Override protected X509Certificate[] doInBackground(Void... params) {
android.os.Debug.waitForDebugger();
if(!SavedAlias.isEmpty())
{
try {
chain = KeyChain.getCertificateChain(getApplicationContext(),SavedAlias);
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
else
{
this.cancel(true);
}
return chain;
}
@Override
protected void onPostExecute(X509Certificate[] chain)
{
if(chain != null)
{
Toast.makeText(getApplicationContext(), "YAY, Certificate is not empty", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "Certificate is Empty", Toast.LENGTH_LONG).show();
}
/*
if (privateKey != null) {
Signature signature = null;
try {
signature = Signature.getInstance("SHA1withRSA");
} catch (NoSuchAlgorithmException e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
try {
signature.initSign(privateKey);
} catch (InvalidKeyException e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
*/
}
}
public void getCertificates(String Host)
{
KeyChainAliasCallback callBack = new KeyChainAliasCallback() {
@Override
public void alias(String alias) {
if (alias != null)
{
Looper.prepare();
saveAlias(alias);
run();
Looper.loop();
}
}
};
KeyChain.choosePrivateKeyAlias(this, callBack,
new String[] {"RSA", "DSA"}, // List of acceptable key types. null for any
null, // issuer, null for any
null, // host name of server requesting the cert, null if unavailable
443, // port of server requesting the cert, -1 if unavailable
null); // alias to preselect, null if unavailable
}
public void saveAlias(String alias)
{
SavedAlias = alias;
}
}
Any help on how to do this would be greatly appreciated as i have never done any authentication before and i have found it difficult to find anything on this topic for android 4.0 as 4.0 seems to be different in implementation then the older versions.
Hi everyone.
I want to retrieve the current cpu frequency in my app but I don't seem to be right.
In my code I want to read the "scaling_cpu_freq" file from internal storage.
This is the code:
Code:
private String ReadCPUMhz() {
String cpuMaxFreq = "";
int cur = 0;
try {
[user=1299008]@supp[/user]ressWarnings("resource")
BufferedReader maxi = new BufferedReader(new FileReader(new File("/sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq")));
try{
cpuMaxFreq = maxi.readLine();
cur = Integer.parseInt(cpuMaxFreq);
cur = cur/1000;
} catch (Exception ex){
ex.printStackTrace();
}
} catch (FileNotFoundException f) {
f.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return String.valueOf(cur);
}
The problem is that the method only returns 0, which is the initial value of the int "cur".
Can anybody help me?
Thanks in advance.
Here's the code I use:
Declare this class in your Activity
Code:
// Read current frequency from /sys in a separate thread
// This class assumes your TextView is declared and referenced in the OnCreate of the class this one is declared in
// And its variable name is mCurCpuFreq
protected class CurCPUThread extends Thread {
private static final String CURRENT_CPU = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq";
private boolean mInterrupt = false;
public void interrupt() {
mInterrupt = true;
}
[user=439709]@override[/user]
public void run() {
try {
while (!mInterrupt) {
sleep(400);
final String curFreq = readOneLine(CURRENT_CPU);
mCurCPUHandler.sendMessage(mCurCPUHandler.obtainMessage(0,
curFreq));
}
} catch (InterruptedException e) {
return;
}
}
}
// Update real-time current frequency & stats in a separate thread
protected static Handler mCurCPUHandler = new Handler() {
public void handleMessage(Message msg) {
mCurFreq.setText(toMHz((String) msg.obj));
final int p = Integer.parseInt((String) msg.obj);
new Thread(new Runnable() {
public void run() {
// Here I update a real-time graph of the current freq
}
}
}).start();
}
};
Helper methods used :
Code:
// Convert raw collected values to formatted MhZ
private static String toMHz(String mhzString) {
if (Integer.valueOf(mhzString) != null)
return String.valueOf(Integer.valueOf(mhzString) / 1000) + " MHz";
else
return "NaN";
}
// Iterate through the /sys file
public static String readOneLine(String fname) {
BufferedReader br;
String line = null;
try {
br = new BufferedReader(new FileReader(fname), 512);
try {
line = br.readLine();
} finally {
br.close();
}
} catch (Exception e) {
Log.e(TAG, "IO Exception when reading sys file", e);
// attempt to do magic!
return readFileViaShell(fname, true);
}
return line;
}
// Backup method if the above one fails
public static String readFileViaShell(String filePath, boolean useSu) {
CommandResult cr = null;
if (useSu) {
cr = new CMDProcessor().runSuCommand("cat " + filePath);
} else {
cr = new CMDProcessor().runShellCommand("cat " + filePath);
}
if (cr.success())
return cr.getStdout();
return null;
}
CMDProcessor.java and its dependencies attached to this post
Moderators... It says I am breaking the rules by asking a question and to ask in the Q&A... But the title of this is "Coding Discussion, Q&A, and Educational Resources" I am not breaking the rules intentionally, I just don't know where else to put this. This is a Coding Question, not a General Question that I would think would get buried and or lost in the General Q&A forum. Please move if you feel I am incorrect.
Hello All, I was hoping someone could help me.
I am trying to create an app that will hide pictures. I want to be able to Pick my App from the Share (Send To) menu from the Users Gallery and have it copy the file to a Directory I have created on my SDCard and then ultimately delete the file from the current location.
Here is what I have so far, but when I pick my app from the Share menu, it crashes the Gallery app. So... I can't even see any errors in my LogCat to even try and troubleshoot my issue.
Can someone point me to a working example of how to do this (I have searched the internet until I am blue in the face) or... I hate to say it... Fix my Code?
Any Help would be appreciated... Thanks!!
Code:
package com.company.privitegallery;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
public class SendToDo extends Activity {
File sdCardLoc = Environment.getExternalStorageDirectory();
File intImagesDir = new File(sdCardLoc,"/DCIM/privgal/.nomedia");
private static final int CAMERA_REQUEST = 1888;
private String selectedImagePath;
String fileName = "capturedImage.jpg";
private static Uri mCapturedImageURI;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
// Get intent, action and MIME type
Intent intent = getIntent();
String action = intent.getAction();
String type = intent.getType();
if (Intent.ACTION_SEND.equals(action) && type != null) {
if ("text/plain".equals(type)) {
handleSendText(intent); // Handle text being sent
} else if (type.startsWith("image/")) {
handleSendImage(intent); // Handle single image being sent
try {
GetPhotoPath();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} else if (Intent.ACTION_SEND_MULTIPLE.equals(action) && type != null) {
if (type.startsWith("image/")) {
handleSendMultipleImages(intent); // Handle multiple images being sent
}
} else {
// Handle other intents, such as being started from the home screen
}
//...
}
void handleSendText(Intent intent) {
String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
if (sharedText != null) {
// Update UI to reflect text being shared
}
}
void handleSendImage(Intent intent) {
Uri imageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);
if (imageUri != null) {
// Update UI to reflect image being shared
}
}
void handleSendMultipleImages(Intent intent) {
ArrayList<Uri> imageUris = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
if (imageUris != null) {
// Update UI to reflect multiple images being shared
}
}
public void GetPhotoPath() throws IOException {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
mCapturedImageURI = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
copy(fileName, intImagesDir);
}
[user=439709]@override[/user]
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_REQUEST) {
selectedImagePath = getPath(mCapturedImageURI);
Log.v("selectedImagePath: ", ""+selectedImagePath);
//Save the path to pass between activities
try {
copy(selectedImagePath, intImagesDir);
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
public void copy(String scr, File dst) throws IOException {
InputStream in = new FileInputStream(scr);
OutputStream 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();
}
private void deleteLatest() {
// TODO Auto-generated method stub
File f = new File(Environment.getExternalStorageDirectory() + "/DCIM/Camera" );
//Log.i("Log", "file name in delete folder : "+f.toString());
File [] files = f.listFiles();
//Log.i("Log", "List of files is: " +files.toString());
Arrays.sort( files, new Comparator<Object>()
{
public int compare(Object o1, Object o2) {
if (((File)o1).lastModified() > ((File)o2).lastModified()) {
// Log.i("Log", "Going -1");
return -1;
} else if (((File)o1).lastModified() < ((File)o2).lastModified()) {
// Log.i("Log", "Going +1");
return 1;
} else {
// Log.i("Log", "Going 0");
return 0;
}
}
});
//Log.i("Log", "Count of the FILES AFTER DELETING ::"+files[0].length());
files[0].delete();
}
}
What's the gallery log output?
Btw, you're not breaking the rules. This is the right forum for Java Q&A.
nikwen said:
What's the gallery log output?
Click to expand...
Click to collapse
How would I get the Logs for the Gallery? I am using and HTC ONE and it's the standard Gallery. Nothing shows up in LogCat so I'm stuck
nikwen said:
Btw, you're not breaking the rules. This is the right forum for Java Q&A.
Click to expand...
Click to collapse
Great, Thanks!!
StEVO_M said:
How would I get the Logs for the Gallery? I am using and HTC ONE and it's the standard Gallery. Nothing shows up in LogCat so I'm stuck
Great, Thanks!!
Click to expand...
Click to collapse
Do you view the logs on your computer?
There should be an error message in the logs.
nikwen said:
Do you view the logs on your computer?
There should be an error message in the logs.
Click to expand...
Click to collapse
Which Logs?? As I said before. LogCat does not give any errors.
Dear all , How are you
I have an Android application , the Developer of it chose to stop the support for it.
Any way i want to fix the bug,
I am not that expert with Java so i am seeking for help
The error that the app return when it get data from the database is :
Code:
11-14 15:42:26.420 W/SQLiteConnectionPool(15763): A SQLiteConnection object for database '/data/data/com.bookscars.src.v65/databases/AppDbStoreroot7' was leaked! Please fix your application to end transactions in progress properly and to close the database when it is no longer needed.
Now i did decompile the APK , search for the class who call AppDbStoreroot7 database to see what we can do for it ! and i found it,
Please note that i need to edit on the Smali code
what i need to know , where i need to put the close commad since i am not a JAVA expert
here is the code :
Code:
package com.studio.sm.root.utility;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.util.Iterator;
import java.util.Vector;
import org.json.JSONArray;
import org.json.JSONObject;
public class RootLogsStorage
{
private static final String DATABASE_NAME = "AppDbStoreroot7";
private static final int DATABASE_VERSION = 1;
public static final String TABLE_BOOKS = "books";
public static final String TABLE_CARS = "cars";
private static final String TAG = "RootLogsStorage";
private DatabaseHelper DBHelper;
private final Context context;
private SQLiteDatabase db;
private RootLogsStorage(Context paramContext)
{
this.context = paramContext;
this.DBHelper = new DatabaseHelper(this.context, null);
}
public static void clearStorage(Context paramContext)
{
RootLogsStorage localRootLogsStorage = getWritable(paramContext);
localRootLogsStorage.emptyLogTable("books");
localRootLogsStorage.emptyLogTable("cars");
localRootLogsStorage.close();
}
private boolean emptyLogTable(String paramString)
{
return this.db.delete(paramString, null, null) > 0;
}
private static String getCreateStringFor(String paramString)
{
return "create table " + paramString + " (_id integer primary key autoincrement, " + "contents text not null);";
}
private Cursor getCursorOf(String paramString)
{
Cursor localCursor = this.db.query(paramString, new String[] { "_id", "contents" }, null, null, null, null, null);
if ((localCursor == null) || (localCursor.getCount() <= 0) || (!localCursor.moveToFirst()))
{
if (localCursor != null) {
localCursor.close();
}
localCursor = null;
}
return localCursor;
}
public static RootLogsStorage getReadable(Context paramContext)
{
return new RootLogsStorage(paramContext).openToRead();
}
public static RootLogsStorage getWritable(Context paramContext)
{
return new RootLogsStorage(paramContext).openToWrite();
}
private RootLogsStorage openToRead()
throws SQLException
{
this.db = this.DBHelper.getReadableDatabase();
return this;
}
private RootLogsStorage openToWrite()
throws SQLException
{
this.db = this.DBHelper.getWritableDatabase();
return this;
}
public void close()
{
this.db.close();
this.DBHelper.close();
}
public JSONArray getLogContentsOf(String paramString)
throws Exception
{
JSONArray localJSONArray = new JSONArray();
Cursor localCursor = getCursorOf(paramString);
if (localCursor == null) {
return localJSONArray;
}
while (!localCursor.isAfterLast())
{
localJSONArray.put(new JSONObject(localCursor.getString(1)));
localCursor.moveToNext();
}
localCursor.close();
return localJSONArray;
}
public void insertLogs(String paramString, Vector<String> paramVector)
{
Log.e("RootLogsStorage INSERT", paramString + "/" + paramVector.size());
Iterator localIterator = paramVector.iterator();
for (;;)
{
if (!localIterator.hasNext()) {
return;
}
String str = (String)localIterator.next();
ContentValues localContentValues = new ContentValues();
localContentValues.put("contents", str);
this.db.insert(paramString, null, localContentValues);
}
}
private static class DatabaseHelper
extends SQLiteOpenHelper
{
private DatabaseHelper(Context paramContext)
{
super("AppDbStoreroot7", null, 1);
}
public void onCreate(SQLiteDatabase paramSQLiteDatabase)
{
paramSQLiteDatabase.execSQL(RootLogsStorage.getCreateStringFor("books"));
paramSQLiteDatabase.execSQL(RootLogsStorage.getCreateStringFor("cars"));
}
public void onUpgrade(SQLiteDatabase paramSQLiteDatabase, int paramInt1, int paramInt2) {}
}
}
Please advice where to put the close command , please note i will edit on smali !
so i have been working on an app for a while now but now my code is crashing due to no empty constructor.
but i have no more idea how i should fix this.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Code:
package com.spacewizz.powersavelauncher;
import java.util.ArrayList;
import java.util.List;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class ChooserAppsSettings extends LinearLayout {
private static final int CAPACITY = 6;
private static final String KEY_LIST[] = { "1", "2", "3", "4", "5", "6"};
private static final String HENABLED_KEY = "com.spacewizz.powersavelauncher.HENABLED";
private static final String KEY_APPNAME_KEY[] = {
"com.spacewizz.powersavelauncher.APP1", "com.spacewizz.powersavelauncher.APP2",
"com.spacewizz.powersavelauncher.APP3", "com.spacewizz.powersavelauncher.APP4",
"com.spacewizz.powersavelauncher.APP5", "com.spacewizz.powersavelauncher.APP6"};
private static final String KEY_INTENTNAME_KEY[] = {
"com.spacewizz.powersavelauncher.INTENT1", "com.spacewizz.powersavelauncher.INTENT2",
"com.spacewizz.powersavelauncher.INTENT3", "com.spacewizz.powersavelauncher.INTENT4",
"com.spacewizz.powersavelauncher.INTENT5", "com.spacewizz.powersavelauncher.INTENT6"};
private static final String KEY_SETTINGS = "com.spacewizz.powersavelauncher.SETTINGS";
private static final String VIEW_MODE_KEY = "com.spacewizz.powersavelauncher.VIEW_MODE_KEY";
private static final String KEY_APPNAME[] = { "ZAPP1", "ZAPP2", "ZAPP3", "ZAPP4", "ZAPP5", "ZAPP6" };
private static final String HORIZONTAL_KEY = "com.spacewizz.powersavelauncher.HORIZONTAL";
private static final String KEY_APPINTENT[] = { "XAPP1", "XAPP2", "XAPP3", "XAPP4", "XAPP5", "XAPP6" };
private static final String KEY_INTENT_ACTION[] = { "IAPP1", "IAPP2",
"IAPP3", "IAPP4", "IAPP5", "IAPP6" };
private ArrayList<String> INSTALLED_PACKAGE = new ArrayList<String>();
private ArrayList<String> APP_NAME = new ArrayList<String>();
private ArrayList<Intent> LAUNCH_ACTIVITY = new ArrayList<Intent>();
private ArrayList<Drawable> APP_ICONS = new ArrayList<Drawable>();
private ArrayList<String> APPS_SHORTCUT = new ArrayList<String>(CAPACITY);
private ArrayAdapter<String> APPS_SHORTCUT_ADAPTER;
private String OPTIONS[] = { "Remove shortcut" };
private String APP_NAMES[] = new String[CAPACITY];
private String OLD_LIST_NAME, NEW_LIST_NAME, INTENT;
private String MODES[] = { "Icon + Label", "Icon only", "Label only",
"Icon + Label (Vertical)" };
Intent mIntent;
boolean horizontal, henabled;
SharedPreferences sp;
ArrayAdapter<String> mSpinnerAdapter;
SharedPreferences.Editor spe;
private Spinner VIEW_MODES;
private ListView APPSLISTVIEW;
private TextView ViewSettingsLabel, AppsListLabel;
private CheckBox HorizontalScroll;
private Context mContext;
int mSpinnerPos;
private LinearLayout THESETTINGS;
private Button mSettings, mDoneSettings;
private ProgressDialog dialog;
private ScrollView mSettingsView;
private Dialog mSettingsDialog;
private WindowManager.LayoutParams WMLP;
public ChooserAppsSettings(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
this.mContext = context;
dialog = new ProgressDialog(mContext);
dialog.setTitle("Please wait...");
dialog.setMessage("Loading installed applications...");
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setCanceledOnTouchOutside(false);
dialog.setCancelable(false);
henabled = getCBState();
setOrientation(LinearLayout.VERTICAL);
setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
LinearLayout.LayoutParams TVLP = new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
TVLP.gravity = Gravity.CENTER_VERTICAL;
mSpinnerPos = getSpinnerPos();
mSettings = new Button(mContext);
mSettings.setText("Settings");
mSettings.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
mDoneSettings = new Button(mContext);
mDoneSettings.setText("Done!");
mDoneSettings.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
THESETTINGS = new LinearLayout(mContext);
THESETTINGS.setOrientation(LinearLayout.VERTICAL);
THESETTINGS.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
mSettingsView = new ScrollView(mContext);
mSettingsView.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
VIEW_MODES = new Spinner(mContext);
VIEW_MODES.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
mSpinnerAdapter = new ArrayAdapter<String>(mContext,
android.R.layout.simple_spinner_item, MODES);
mSpinnerAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
VIEW_MODES.setAdapter(mSpinnerAdapter);
VIEW_MODES.setSelection(mSpinnerPos);
LinearLayout.LayoutParams ColorLL = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT, 50);
ColorLL.bottomMargin = 30;
ColorLL.topMargin = 20;
ColorLL.leftMargin = 50;
ColorLL.rightMargin = 50;
ViewSettingsLabel = new TextView(mContext);
AppsListLabel = new TextView(mContext);
ViewSettingsLabel.setLayoutParams(TVLP);
AppsListLabel.setLayoutParams(TVLP);
ViewSettingsLabel.setText("Display Options");
AppsListLabel.setText("App Shortcuts List: ");
ViewSettingsLabel.setBackgroundResource(android.R.drawable.title_bar);
AppsListLabel.setBackgroundResource(android.R.drawable.title_bar);
ViewSettingsLabel.setGravity(Gravity.CENTER);
HorizontalScroll = new CheckBox(mContext);
HorizontalScroll.setLayoutParams(TVLP);
HorizontalScroll.setText("Horizontal Scroll (Icon only)");
HorizontalScroll.setEnabled(horizontal);
HorizontalScroll.setChecked(henabled);
APPSLISTVIEW = new ListView(mContext);
APPSLISTVIEW.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
addView(APPSLISTVIEW);
mSettingsDialog = new Dialog(mContext);
mSettingsDialog.setTitle("Settings");
mSettingsDialog.requestWindowFeature(Window.FEATURE_LEFT_ICON);
mSettingsDialog.setContentView(mSettingsView);
mSettingsDialog.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON,
android.R.drawable.ic_menu_manage);
WMLP = new WindowManager.LayoutParams();
WMLP.copyFrom(mSettingsDialog.getWindow().getAttributes());
WMLP.width = WindowManager.LayoutParams.MATCH_PARENT;
WMLP.height = WindowManager.LayoutParams.WRAP_CONTENT;
for (int i = 1; i <= CAPACITY; i++) {
APPS_SHORTCUT.add("Application " + String.valueOf(i));
}
APPS_SHORTCUT_ADAPTER = new ArrayAdapter<String>(context,
android.R.layout.simple_list_item_1, APPS_SHORTCUT);
dialog.show();
preloadInstalledApplications Preload = new preloadInstalledApplications();
Preload.execute(02, 23, 1997);
setHorizontalScrollListener();
//setViewModeOnItemSelectedListener();
setAppListViewOnClickListener();
setApplistViewOnLongClickListener();
//setmSettingsOnClickListener();
//setmDoneSettingsOnClickListener();
loadList();
refreshList();
}
private boolean getCBState() {
sp = PreferenceManager.getDefaultSharedPreferences(mContext);
return sp.getBoolean(HENABLED_KEY, false);
}
private void saveCBState(boolean state) {
openSPE();
spe.putBoolean(HENABLED_KEY, state);
commitSPE();
}
private boolean getHorizontal() {
sp = PreferenceManager.getDefaultSharedPreferences(mContext);
return sp.getBoolean(HORIZONTAL_KEY, false);
}
private void setHorizontalScrollListener() {
// TODO Auto-generated method stub
HorizontalScroll
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
if (HorizontalScroll.isChecked()) {
saveCBState(HorizontalScroll.isChecked());
} else {
saveCBState(HorizontalScroll.isChecked());
}
}
});
}
private void setmDoneSettingsOnClickListener() {
// TODO Auto-generated method stub
mDoneSettings.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (mSettingsDialog.isShowing()) {
mSettingsDialog.dismiss();
}
}
});
}
private void setmSettingsOnClickListener() {
// TODO Auto-generated method stub
mSettings.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mSettingsDialog.show();
mSettingsDialog.getWindow().setAttributes(WMLP);
}
});
}
private void setViewModeOnItemSelectedListener() {
// TODO Auto-generated method stub
VIEW_MODES.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
mSpinnerPos = arg2;
int MODE = mSpinnerPos;
VIEW_MODES.setSelection(mSpinnerPos);
saveSpinnerPos(mSpinnerPos);
if (mSpinnerPos == 1) {
horizontal = true;
henabled = HorizontalScroll.isChecked();
if (henabled) {
MODE = 100;
} else {
MODE = mSpinnerPos;
}
} else {
horizontal = false;
henabled = false;
}
sendViewModeSettings(MODE);
HorizontalScroll.setEnabled(horizontal);
openSPE();
spe.putBoolean(HORIZONTAL_KEY, horizontal);
commitSPE();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
VIEW_MODES.setSelection(mSpinnerPos);
}
});
}
private void saveSpinnerPos(int pos) {
sp = PreferenceManager.getDefaultSharedPreferences(getContext());
spe = sp.edit();
spe.putInt(VIEW_MODE_KEY, pos);
spe.commit();
}
private int getSpinnerPos() {
sp = PreferenceManager.getDefaultSharedPreferences(getContext());
return sp.getInt(VIEW_MODE_KEY, 0);
}
private void sendViewModeSettings(int mode) {
mIntent = new Intent();
mIntent.setAction(KEY_SETTINGS);
mIntent.putExtra(VIEW_MODE_KEY, mode);
mContext.sendBroadcast(mIntent);
}
private void setApplistViewOnLongClickListener() {
// TODO Auto-generated method stub
APPSLISTVIEW.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
final int arg2, long arg3) {
// TODO Auto-generated method stub
final ListAdapter OPTIONSMENU = new ArrayAdapter<String>(
mContext, android.R.layout.simple_list_item_1, OPTIONS);
new AlertDialog.Builder(mContext)
.setTitle("Options")
.setIcon(android.R.drawable.ic_dialog_info)
.setAdapter(OPTIONSMENU,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
switch (which) {
case 0:
String NEW_ITEM = "Application "
+ String.valueOf(arg2 + 1)
+ " (Not on SystemUI)";
APPS_SHORTCUT.remove(arg2);
APPS_SHORTCUT.add(arg2, NEW_ITEM);
sendDeleteCommand(arg2);
APP_NAMES[arg2] = APPS_SHORTCUT
.get(arg2);
saveList(arg2);
refreshList();
break;
}
}
}).show();
return false;
}
});
}
private void setAppListViewOnClickListener() {
// TODO Auto-generated method stub
APPSLISTVIEW.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1,
final int arg2, long arg3) {
// TODO Auto-generated method stub
final ListAdapter ADAPTER = new ArrayAdapter<String>(mContext,
android.R.layout.simple_list_item_1, APP_NAME);
new AlertDialog.Builder(mContext)
.setTitle("Select Application")
.setIcon(android.R.drawable.ic_dialog_alert)
.setAdapter(ADAPTER,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
Toast.makeText(
getContext(),
"Application "
+ String.valueOf(arg2 + 1)
+ " selected: "
+ ADAPTER
.getItem(which)
.toString(),
Toast.LENGTH_SHORT).show();
OLD_LIST_NAME = APPS_SHORTCUT.get(arg2);
NEW_LIST_NAME = ADAPTER.getItem(which)
.toString();
if (OLD_LIST_NAME != NEW_LIST_NAME) {
APPS_SHORTCUT.remove(arg2);
String NEW_ITEM = ADAPTER.getItem(
which).toString();
APPS_SHORTCUT.add(arg2, NEW_ITEM);
if (LAUNCH_ACTIVITY.get(which) != null) {
INTENT = INSTALLED_PACKAGE
.get(which);
} else {
INTENT = "null";
}
refreshToBePassed(arg2, NEW_ITEM,
INTENT);
}
saveList(arg2);
refreshList();
}
}).show();
}
});
}
private void refreshList() {
APPS_SHORTCUT_ADAPTER = new ArrayAdapter<String>(mContext,
android.R.layout.simple_list_item_1, APPS_SHORTCUT);
APPSLISTVIEW.setAdapter(APPS_SHORTCUT_ADAPTER);
}
private void refreshToBePassed(int position, String APP, String mINTENT) {
APP_NAMES[position] = APP;
KEY_APPNAME[position] = APPS_SHORTCUT_ADAPTER.getItem(position);
KEY_APPINTENT[position] = mINTENT;
mIntent = new Intent();
mIntent.setAction(KEY_INTENT_ACTION[position]);
mIntent.putExtra(KEY_APPNAME_KEY[position], KEY_APPNAME[position]);
mIntent.putExtra(KEY_INTENTNAME_KEY[position], KEY_APPINTENT[position]);
mContext.sendBroadcast(mIntent);
}
private void saveList(int position) {
sp = PreferenceManager.getDefaultSharedPreferences(getContext());
spe = sp.edit();
spe.putString(KEY_LIST[position], APP_NAMES[position]);
spe.commit();
}
private void loadList() {
// TODO Auto-generated method stub
sp = PreferenceManager.getDefaultSharedPreferences(getContext());
APPS_SHORTCUT.clear();
for (int x = 0; x < CAPACITY; x++) {
APP_NAMES[x] = sp.getString(KEY_LIST[x],
"Application " + String.valueOf((x + 1)));
APPS_SHORTCUT.add(APP_NAMES[x]);
}
}
private void sendDeleteCommand(int position) {
KEY_APPNAME[position] = "DELETE";
KEY_APPINTENT[position] = "DELETE";
mIntent = new Intent();
mIntent.setAction(KEY_INTENT_ACTION[position]);
mIntent.putExtra(KEY_APPNAME_KEY[position], KEY_APPNAME[position]);
mIntent.putExtra(KEY_INTENTNAME_KEY[position], KEY_APPINTENT[position]);
mContext.sendBroadcast(mIntent);
}
private void openSPE() {
sp = PreferenceManager.getDefaultSharedPreferences(mContext);
spe = sp.edit();
}
private void commitSPE() {
spe.commit();
}
private class preloadInstalledApplications extends
AsyncTask<Integer, Void, Void> {
@Override
protected Void doInBackground(Integer... params) {
// TODO Auto-generated method stub
final PackageManager PM = mContext.getPackageManager();
List<ApplicationInfo> PACKAGES = PM
.getInstalledApplications(PackageManager.GET_META_DATA);
for (ApplicationInfo PACKAGE_INFO : PACKAGES) {
if (PM.getLaunchIntentForPackage(PACKAGE_INFO.packageName) != null) {
INSTALLED_PACKAGE.add(PACKAGE_INFO.packageName);
LAUNCH_ACTIVITY
.add(PM.getLaunchIntentForPackage(PACKAGE_INFO.packageName));
APP_ICONS.add(PM.getApplicationIcon(PACKAGE_INFO));
APP_NAME.add(PM.getApplicationLabel(PACKAGE_INFO)
.toString());
}
}
return null;
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialog.dismiss();
}
}
}
anyone knows how to fix?
thanks
This' to put it inns nutshell
haaaroldb said:
This' to put it inns nutshell
Click to expand...
Click to collapse
I am sorry i don't understand. can you explain ?
I am not sure, but your class might be missing constructor
more info: http://www.javatpoint.com/constructor
For some reason it says that it needs and Empty constructor.
Type inside ChooserAppSettings class:
Code:
public ChooserAppSettings(){
}
This may fix it. I am not sure though why it needs the empty constructor. What class is your ChooserAppSettings extending or implementing??
Can you show all the logcat messages?
@mmdeveloper said:
For some reason it says that it needs and Empty constructor.
Type inside ChooserAppSettings class:
Code:
public ChooserAppSettings(){
}
This may fix it. I am not sure though why it needs the empty constructor. What class is your ChooserAppSettings extending or implementing??
Can you show all the logcat messages?
Click to expand...
Click to collapse
Linearlayout.
Tried the above but didnt worked
Try adding these:
Code:
public ChooserAppSettings(Context context){
super(context);
}
public ChooserAppSettings(Context context, AttributeSet attrs, int defStyle){
super(context, attrs, defStyle);
}
Issue solved.
was a stupid fault of myself xD
typo at launching the java file