[Q] Copy Image from Gallery Share (Send To) menu - Java for Android App Development

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.

Related

[Q] Shoutcast ICY to Http (Eclair compatible)

Hi.
I'm currently working on a wakeup-app (alarm) that plays your favorite radio-station via shoutcast-stream.
It looked really easy:
Code:
MediaPlayer mp = new MediaPlayer();
mp.setDataSource(PATH_TO_FILE);
mp.prepare();
mp.start();
Then I found out Eclair doesn't support shoutcast's ICY protocol. Grmbl.
So for 2.1 (and earlier versions) it is required to handle the shoutcast-stream seperatly and pass it to MediaPlayer via http.
I even found an example:
http://code.google.com/p/npr-android-app/source/browse/trunk/Npr/src/org/npr/android/news/StreamProxy.java
Problem is that it's all a bit too advanced for me, so I was wondering if anyone has a really simple example of how to do this?
Something like:
"Add 'this file' to your project (where 'this file' would be a class similarly to StreamProxy) and then add this to your application:"
Code:
StreamProxy sp = new StreamProxy();
sp.setDataSource( SHOUTCAST_URL );
MediaPlayer mp = new MediaPlayer();
mp.setDataSource( sp.getProxyUrl );
mp.prepare();
mp.start();
(Pardon my english
fixed!
Will post how I did it soon.
Here's the app:
http://android.rejh.nl/fmalarm
Just got reminded by someone that I never posted the solution. Here goes:
Code:
// Streamurl
String streamUrl = "[Path-to-audio-stream-or-file]";
// Prepare Proxy (for Android 2.1 en lower (sdk<8))
sdkVersion = 0;
try { sdkVersion = Integer.parseInt(Build.VERSION.SDK); } // Note: Build.VERSION.SDK is deprecated..
catch (NumberFormatException e) {}
if (sdkVersion<8) {
if (proxy==null) {
try {
proxy = new StreamProxy();
proxy.init();
proxy.start();
streamUrl = String.format("http://127.0.0.1:%d/%s", proxy.getPort(), url);
} catch(IllegalStateException e) { Log.e(LOGTAG," -> IllStateException: "+e, e); }
}
}
// Create mediaplayer and set stream (proxied if needed)
mp = new MediaPlayer();
mp.setDataSource(streamUrl);
UPDATE!! Forgot the StreamProxy code
Code:
// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Minor changes by REJH Gadellaa 2010/2011
package org.npr.android.news;
import android.util.Log;
import org.apache.http.Header;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseFactory;
import org.apache.http.ParseException;
import org.apache.http.ProtocolVersion;
import org.apache.http.RequestLine;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ClientConnectionOperator;
import org.apache.http.conn.OperatedClientConnection;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.DefaultClientConnection;
import org.apache.http.impl.conn.DefaultClientConnectionOperator;
import org.apache.http.impl.conn.DefaultResponseParser;
import org.apache.http.impl.conn.SingleClientConnManager;
import org.apache.http.io.HttpMessageParser;
import org.apache.http.io.SessionInputBuffer;
import org.apache.http.message.BasicHttpRequest;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.message.BasicLineParser;
import org.apache.http.message.ParserCursor;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.CharArrayBuffer;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.StringTokenizer;
public class StreamProxy implements Runnable {
private static final String LOG_TAG = "FMA2Proxy";
private int port = 5050;
public int getPort() {
return port;
}
private boolean isRunning = true;
private ServerSocket socket;
private Thread thread;
public void init() {
try {
socket = new ServerSocket(port, 0, InetAddress.getByAddress(new byte[] {127,0,0,1}));
socket.setSoTimeout(5000);
port = socket.getLocalPort();
Log.d(LOG_TAG, "port " + port + " obtained");
} catch (UnknownHostException e) {
Log.e(LOG_TAG, "Error initializing server", e);
} catch (IOException e) {
Log.e(LOG_TAG, "Error initializing server", e);
}
}
public void start() {
if (socket == null) {
throw new IllegalStateException("Cannot start proxy; it has not been initialized.");
}
thread = new Thread(this);
thread.start();
}
public void stop() {
isRunning = false;
if (thread == null) {
throw new IllegalStateException("Cannot stop proxy; it has not been started.");
}
if (socket!=null) { try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} }
thread.interrupt();
try {
thread.join(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// @Override
public void run() {
Log.d(LOG_TAG, "running");
while (isRunning) {
try {
Socket client = socket.accept();
if (client == null) {
continue;
}
Log.d(LOG_TAG, "client connected");
HttpRequest request = readRequest(client);
processRequest(request, client);
} catch (SocketTimeoutException e) {
// Do nothing
} catch (IOException e) {
Log.e(LOG_TAG, "Error connecting to client", e);
}
}
Log.d(LOG_TAG, "Proxy interrupted. Shutting down.");
}
private HttpRequest readRequest(Socket client) {
HttpRequest request = null;
InputStream is;
String firstLine;
try {
is = client.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
firstLine = reader.readLine();
} catch (IOException e) {
Log.e(LOG_TAG, "Error parsing request", e);
return request;
}
if (firstLine == null) {
Log.i(LOG_TAG, "Proxy client closed connection without a request.");
return request;
}
StringTokenizer st = new StringTokenizer(firstLine);
String method = st.nextToken();
String uri = st.nextToken();
Log.d(LOG_TAG, uri);
String realUri = uri.substring(1);
Log.d(LOG_TAG, realUri);
request = new BasicHttpRequest(method, realUri);
return request;
}
private HttpResponse download(String url) {
DefaultHttpClient seed = new DefaultHttpClient();
SchemeRegistry registry = new SchemeRegistry();
registry.register(
new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
SingleClientConnManager mgr = new MyClientConnManager(seed.getParams(),
registry);
DefaultHttpClient http = new DefaultHttpClient(mgr, seed.getParams());
HttpGet method = new HttpGet(url);
HttpResponse response = null;
try {
Log.d(LOG_TAG, "starting download");
response = http.execute(method);
Log.d(LOG_TAG, "downloaded");
} catch (ClientProtocolException e) {
Log.e(LOG_TAG, "Error downloading", e);
} catch (IOException e) {
Log.e(LOG_TAG, "Error downloading", e);
}
return response;
}
private void processRequest(HttpRequest request, Socket client)
throws IllegalStateException, IOException {
if (request == null) {
return;
}
Log.d(LOG_TAG, "processing");
String url = request.getRequestLine().getUri();
HttpResponse realResponse = download(url);
if (realResponse == null) {
return;
}
Log.d(LOG_TAG, "downloading...");
InputStream data = realResponse.getEntity().getContent();
StatusLine line = realResponse.getStatusLine();
HttpResponse response = new BasicHttpResponse(line);
response.setHeaders(realResponse.getAllHeaders());
Log.d(LOG_TAG, "reading headers");
StringBuilder httpString = new StringBuilder();
httpString.append(response.getStatusLine().toString());
httpString.append("\n");
for (Header h : response.getAllHeaders()) {
httpString.append(h.getName()).append(": ").append(h.getValue()).append(
"\n");
}
httpString.append("\n");
Log.d(LOG_TAG, "headers done");
try {
byte[] buffer = httpString.toString().getBytes();
int readBytes = -1;
Log.d(LOG_TAG, "writing to client");
client.getOutputStream().write(buffer, 0, buffer.length);
// Start streaming content.
byte[] buff = new byte[1024 * 50];
while (isRunning && (readBytes = data.read(buff, 0, buff.length)) != -1) {
client.getOutputStream().write(buff, 0, readBytes);
}
} catch (Exception e) {
Log.e("", e.getMessage(), e);
} finally {
if (data != null) {
data.close();
}
client.close();
}
}
private class IcyLineParser extends BasicLineParser {
private static final String ICY_PROTOCOL_NAME = "ICY";
private IcyLineParser() {
super();
}
@Override
public boolean hasProtocolVersion(CharArrayBuffer buffer,
ParserCursor cursor) {
boolean superFound = super.hasProtocolVersion(buffer, cursor);
if (superFound) {
return true;
}
int index = cursor.getPos();
final int protolength = ICY_PROTOCOL_NAME.length();
if (buffer.length() < protolength)
return false; // not long enough for "HTTP/1.1"
if (index < 0) {
// end of line, no tolerance for trailing whitespace
// this works only for single-digit major and minor version
index = buffer.length() - protolength;
} else if (index == 0) {
// beginning of line, tolerate leading whitespace
while ((index < buffer.length()) &&
HTTP.isWhitespace(buffer.charAt(index))) {
index++;
}
} // else within line, don't tolerate whitespace
if (index + protolength > buffer.length())
return false;
return buffer.substring(index, index + protolength).equals(ICY_PROTOCOL_NAME);
}
@Override
public Header parseHeader(CharArrayBuffer buffer) throws ParseException {
return super.parseHeader(buffer);
}
@Override
public ProtocolVersion parseProtocolVersion(CharArrayBuffer buffer,
ParserCursor cursor) throws ParseException {
if (buffer == null) {
throw new IllegalArgumentException("Char array buffer may not be null");
}
if (cursor == null) {
throw new IllegalArgumentException("Parser cursor may not be null");
}
final int protolength = ICY_PROTOCOL_NAME.length();
int indexFrom = cursor.getPos();
int indexTo = cursor.getUpperBound();
skipWhitespace(buffer, cursor);
int i = cursor.getPos();
// long enough for "HTTP/1.1"?
if (i + protolength + 4 > indexTo) {
throw new ParseException
("Not a valid protocol version: " +
buffer.substring(indexFrom, indexTo));
}
// check the protocol name and slash
if (!buffer.substring(i, i + protolength).equals(ICY_PROTOCOL_NAME)) {
return super.parseProtocolVersion(buffer, cursor);
}
cursor.updatePos(i + protolength);
return createProtocolVersion(1, 0);
}
@Override
public RequestLine parseRequestLine(CharArrayBuffer buffer,
ParserCursor cursor) throws ParseException {
return super.parseRequestLine(buffer, cursor);
}
@Override
public StatusLine parseStatusLine(CharArrayBuffer buffer,
ParserCursor cursor) throws ParseException {
StatusLine superLine = super.parseStatusLine(buffer, cursor);
return superLine;
}
}
class MyClientConnection extends DefaultClientConnection {
@Override
protected HttpMessageParser createResponseParser(
final SessionInputBuffer buffer,
final HttpResponseFactory responseFactory, final HttpParams params) {
return new DefaultResponseParser(buffer, new IcyLineParser(),
responseFactory, params);
}
}
class MyClientConnectionOperator extends DefaultClientConnectionOperator {
public MyClientConnectionOperator(final SchemeRegistry sr) {
super(sr);
}
@Override
public OperatedClientConnection createConnection() {
return new MyClientConnection();
}
}
class MyClientConnManager extends SingleClientConnManager {
private MyClientConnManager(HttpParams params, SchemeRegistry schreg) {
super(params, schreg);
}
@Override
protected ClientConnectionOperator createConnectionOperator(
final SchemeRegistry sr) {
return new MyClientConnectionOperator(sr);
}
}
}

Problem of flashlight app code (Eclipse)

Hello everyone ..
I have problem on developing a flashlight app
I tried the solutions that provided by Eclipse but none solved the problem
or even make any sense to me :angel:
every "Void" statement on the code appeared as an error
and i don't know why .. also i'm sure that everything on the code is correct
Examples of the errors:
private void playSound() {
private void toggleButtonImage() {
private void turnOffFlash() {
and .. etc , i got an error on every "Void" !
so.. i'm waiting for your opinions
Thanks in advance )​
Hi,
It is impossible for us to tell you what you have done wrong if you do not post your source code.
It could be just one character missing somewhere or one to much.
We need your code to help you.
(If you do not want to release it completely, copy your project and remove those parts you do not want us to see. This could also help you with finding the error yourself. )
nikwen said:
Hi,
It is impossible for us to tell you what you have done wrong if you do not post your source code.
It could be just one character missing somewhere or one to much.
We need your code to help you.
(If you do not want to release it completely, copy your project and remove those parts you do not want us to see. This could also help you with finding the error yourself. )
Click to expand...
Click to collapse
Thanks 4 answering me nikwen
i tried to post a screenshot of the problem but i'm a new member in the forum so i couldn't post an external link
anyway .. here's the Code
package com.mohamedsherif.flashlighttorch;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ToggleButton;
public class MainActivity extends Activity {
ImageButton switchButton;
private Camera camera;
private boolean isFlashOn;
private boolean hasFlash;
Parameters params;
MediaPlayer mp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.switchButton);
//Check if the Device has Flash
hasFlash = getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if(!hasFlash) {
AlertDialog alert = new AlertDialog.Builder(MainActivity.this).create();
alert.setTitle("Error! ");
alert.setMessage("Sorry! .. Your device doesn't have a flash!");
alert.setButton("ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(final DialogInterface dialog, final int which) {
finish();
}
});
alert.show();
return;
}
//Getting camera parameters
private void getCamera() {
if (camera == null) {
try {
camera = Camera.open();
params = camera.getParameters();
} catch (RuntimeException e) {
Log.e("Camera Error. Failed to open. Error", e.getMessage());
}
}
}
private void turnOnFlash() {
if (!hasFlash) {
if (camera == null || params == null) {
return;
}
playSound();
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
toggleButtonImage();
}
}
//Turning off flash
private void turnOffFlash() {
if (isFlashOn) {
if (camera == null || params == null) {
return;
}
playSound();
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isFlashOn = false;
toggleButtonImage();
}
};
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (isFlashOn) {
turnOffFlash();
} else {
turnOnFlash();
}
}
});
// Toggle buttons images
private void toggleButtonImage() {
if (isFlashOn) {
switchButton.setImageResource(R.drawable.switch_on);
} else {
switchButton.setImageResource(R.drawable.switch_off);
}
}
// Playing Sound
private void playSound() {
if (isFlashOn) {
mp = MediaPlayer.create(MainActivity.this, R.raw.light_switch_off);
} else {
mp = MediaPlayer.create(MainActivity.this, R.raw.light_switch_on);
}
mp.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
mp.start();
}
}
@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;
}
}
Click to expand...
Click to collapse
the errors are in RED ​
little changes
private static Camera camera;
private boolean isFlashOn;
private boolean hasFlash;
Parameters params;
MediaPlayer mp;
ToggleButton switchButton;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_flashlight);
getCamera();
switchButton = (ToggleButton) findViewById(R.id.tglOnOffFlashlight);
switchButton.setOnClickListener(new View.OnClickListener() {
@override
public void onClick(View v) {
if (isFlashOn) {
turnOffFlash();
} else {
turnOnFlash();
}
}
});
//Check if the Device has Flash
hasFlash = getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if(!hasFlash) {
AlertDialog alert = new AlertDialog.Builder(FlashlightActivity.this).create();
alert.setTitle("Error! ");
alert.setMessage("Sorry! .. Your device doesn't have a flash!");
alert.setButton("ok", new DialogInterface.OnClickListener() {
@override
public void onClick(final DialogInterface dialog, final int which) {
finish();
}
});
alert.show();
return;
}
}
//Getting camera parameters
private void getCamera() {
if (camera == null) {
try {
camera = Camera.open();
params = camera.getParameters();
} catch (RuntimeException e) {
Log.e("Camera Error. Failed to open. Error", e.getMessage());
}
}
}
private void turnOnFlash() {
if (hasFlash) {
if (camera == null || params == null) {
return;
}
playSound();
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
toggleButtonImage();
}
}
//Turning off flash
private void turnOffFlash() {
if (isFlashOn) {
if (camera == null || params == null) {
return;
}
playSound();
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isFlashOn = false;
toggleButtonImage();
}
}
// Toggle buttons images
private void toggleButtonImage() {
if (isFlashOn) {
switchButton.setBackgroundResource(R.drawable.on_yellow );
} else {
switchButton.setBackgroundResource(R.drawable.off_white);
}
}
// Playing Sound
private void playSound() {
if (isFlashOn) {
mp = MediaPlayer.create(FlashlightActivity.this, R.raw.light_switch_off);
} else {
mp = MediaPlayer.create(FlashlightActivity.this, R.raw.light_switch_on);
}
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
mp.start();
}
these work
Does it work on other projects?
It is working for him, so I guess that the errors are not in the code but maybe your project setup or your installation of Eclipse and the Android SDK is the reason for that.
So to quote myself " Does it work on other projects?".
---------- Post added at 09:59 PM ---------- Previous post was at 09:55 PM ----------
Oh no, there are mistakes with the brackets.
For example you set a listener somewhere inside a methods. However, you forgot to close the bracket (I mean these ones {}). So it ends with a semicolon. It wants more lines of code.
So check your brackets.
Void methods should not return anything. So you can remove all 'return' words in the void methods.
Sent from my NexusHD2 using xda app-developers app
Eztys said:
Void methods should not return anything. So you can remove all 'return' words in the void methods.
Sent from my NexusHD2 using xda app-developers app
Click to expand...
Click to collapse
These returns ARE allowed. They are not necessary but allowed. You can stop the method by this.
It is really a problem with these brackets {}.
krsln said:
private static Camera camera;
private boolean isFlashOn;
private boolean hasFlash;
Parameters params;
MediaPlayer mp;
ToggleButton switchButton;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_flashlight);
getCamera();
switchButton = (ToggleButton) findViewById(R.id.tglOnOffFlashlight);
switchButton.setOnClickListener(new View.OnClickListener() {
@override
public void onClick(View v) {
if (isFlashOn) {
turnOffFlash();
} else {
turnOnFlash();
}
}
these work
Click to expand...
Click to collapse
the same problem with the Void errors !! -.-
nikwen said:
Does it work on other projects?
It is working for him, so I guess that the errors are not in the code but maybe your project setup or your installation of Eclipse and the Android SDK is the reason for that.
So to quote myself " Does it work on other projects?".
---------- Post added at 09:59 PM ---------- Previous post was at 09:55 PM ----------
Oh no, there are mistakes with the brackets.
For example you set a listener somewhere inside a methods. However, you forgot to close the bracket (I mean these ones {}). So it ends with a semicolon. It wants more lines of code.
So check your brackets.
Click to expand...
Click to collapse
i tried the code on a new project but i got the same errors
also i don't think there's any problem with the brackets ?
Eztys said:
Void methods should not return anything. So you can remove all 'return' words in the void methods.
Sent from my NexusHD2 using xda app-developers app
Click to expand...
Click to collapse
the return is not the problem ​
i just solved the void errors but the app is not running on the virtual device !
"the app has stopped unexpectedly"
can anyone try the code ? or even tell me what's wrong ?
BTW the code doesn't contain any errors now .. not even the void errors
package com.mohamedsherif.flashlighttorch;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
public class MainActivity extends Activity {
ImageButton switchButton;
private Camera camera;
private boolean isFlashOn;
private boolean hasFlash;
Parameters params;
MediaPlayer mp;
@SuppressWarnings("deprecation")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.switchButton);
//Check if the Device has Flash
hasFlash = getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if(!hasFlash) {
AlertDialog alert = new AlertDialog.Builder(MainActivity.this).create();
alert.setTitle("Error! ");
alert.setMessage("Sorry! .. Your device doesn't have a flash!");
alert.setButton("ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(final DialogInterface dialog, final int which) {
finish();
}
});
alert.show();
return;
}
getCamera();
toggleButtonImage();
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (isFlashOn) {
turnOffFlash();
} else {
turnOnFlash();
}
}
});
}
//Getting camera parameters
private void getCamera() {
if (camera == null) {
try {
camera = Camera.open();
params = camera.getParameters();
} catch (RuntimeException e) {
Log.e("Camera Error. Failed to open. Error: ", e.getMessage());
}
}
}
private void turnOnFlash() {
if (!hasFlash) {
if (camera == null || params == null) {
return;
}
playSound();
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
toggleButtonImage();
}
}
//Turning off flash
private void turnOffFlash() {
if (isFlashOn) {
if (camera == null || params == null) {
return;
}
playSound();
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isFlashOn = false;
toggleButtonImage();
}
};
// Toggle buttons images
private void toggleButtonImage() {
if (isFlashOn) {
switchButton.setImageResource(R.drawable.switch_on);
} else {
switchButton.setImageResource(R.drawable.switch_off);
}
}
// Playing Sound
private void playSound() {
if (isFlashOn) {
mp = MediaPlayer.create(MainActivity.this, R.raw.light_switch_off);
} else {
mp = MediaPlayer.create(MainActivity.this, R.raw.light_switch_on);
}
mp.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
mp.start();
}
@Override
protected void onDestroy() {
super.onDestroy();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
turnOffFlash();
}
@Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
if (hasFlash)
turnOnFlash();
}
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
getCamera();
}
@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
if (camera != null) {
camera.release();
camera = null;
}
}
@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;
}
}
Click to expand...
Click to collapse
M. Sherif said:
i just solved the void errors but the app is not running on the virtual device !
"the app has stopped unexpectedly"
can anyone try the code ? or even tell me what's wrong ?
BTW the code doesn't contain any errors now .. not even the void errors
​
Click to expand...
Click to collapse
There will be a logcat. Post it here.

[APP] Android transation helper script

If your application has different language versions and a lot of changess to strings.xml (strings added, IDs renamed, strings deleted), the translations will soon become a mess and people won't know anymore what is there left to be translated or if particular string needs translation at all. To fix that I've created a simple java proggy, that
1) loads English strings as a golden source for all other strings
2) compares each values-xx/strings.xml to the above
3) adds a XML comment <!-- PLEASE TRANSLATE --> to each missing value
4) outputs modified to values-xx/strings.xml_obr, sorted by ID
Fast and easy. Here's the code (note: requires jdom-2.x.x.jar)
Code:
package pl.qus.utility.ash;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import org.jdom2.Comment;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
public class AndroidStringsHelper {
private class KeyVal {
String key;
String value;
public KeyVal(String k, String v)
{
key=k;
value=v;
}
}
String resDir = "";
ArrayList<File> listaJęzyków = new ArrayList<File>();
HashMap<String, String> wzorcowaMapa = new HashMap<String, String>();
HashMap<String, String> obrabianaMapa = new HashMap<String, String>();
private static String trKey="!#---TRANSLATE---#!";
public AndroidStringsHelper(String resourceDir) {
String[] listaPlików;
resDir = resourceDir;
File katalog = new File(resDir);
listaPlików = katalog.list();
for (int i = 0; i < listaPlików.length; i++) {
File obr = new File(resourceDir,listaPlików[i]);
if (obr.getName().startsWith("values")) {
File plik=new File(obr, "strings.xml");
if (plik.exists()) {
System.out.println("Dodaję:" + obr.getName());
if (obr.getName().equals("values"))
{
}
else
listaJęzyków.add(plik);
}
}
}
obróbJęzyki();
}
private void obróbJęzyki() {
zaczytajPlik(new File(resDir,"values\\strings.xml"),wzorcowaMapa);
List<KeyVal> sortowanaMapa = new ArrayList<KeyVal>();
for(File plik:listaJęzyków) {
sortowanaMapa.clear();
System.out.println("==================================");
System.out.println("Obrabiam:"+plik.getPath());
obrabianaMapa.clear();
zaczytajPlik(plik,obrabianaMapa);
SortedSet<String> sorted=new TreeSet<String>(wzorcowaMapa.keySet());
Iterator<String> it = sorted.iterator();
while(it.hasNext()) {
String klucz=it.next();
if(obrabianaMapa.containsKey(klucz))
{
sortowanaMapa.add(new KeyVal(klucz, obrabianaMapa.get(klucz)));
}
else
{
System.out.println("Brak ["+klucz+"]");
sortowanaMapa.add(new KeyVal(klucz, trKey+wzorcowaMapa.get(klucz)));
}
}
zapiszPlik(new File(plik.getPath()+"_obr"),sortowanaMapa);
}
}
private void zapiszPlik(File plik, List<KeyVal> docel) {
FileOutputStream os;
Document profileDoc = new Document();
Element root=new Element("resources");
Iterator<KeyVal> it = docel.iterator();
while(it.hasNext()) {
KeyVal nast=it.next();
String klucz=(String) nast.key;
String wart=(String) nast.value;
Element nowy=new Element("string");
if(wart.startsWith(trKey))
{
wart=wart.substring(trKey.length());
root.addContent(new Comment("PLEASE TRANSLATE!"));
}
nowy.addContent(wart);
nowy.setAttribute("name", klucz);
root.addContent(nowy);
}
profileDoc.addContent(root);
try {
os = new FileOutputStream(plik);
XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
outputter.output(profileDoc, os);
os.close();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void zaczytajPlik(File plik, HashMap<String, String> docel) {
SAXBuilder builder = new SAXBuilder();
try {
Document strings = builder.build(plik);
Element spis = strings.getRootElement();
List<Element> wszystkie = spis.getChildren();
for (Element e : wszystkie) {
docel.put(e.getAttributeValue("name"), e.getText());
}
} catch (JDOMException | IOException e) {
e.printStackTrace();
}
System.out.println("Zaczytane:"+docel.size());
}
}
To run it just pass a path to your resource directory:
Code:
public class Main {
public static void main(String arg[]) {
new AndroidStringsHelper("/path/to/your/workspace/project/res");
}
}

[Q] I want to fix a bug inside APK app! (A SQLiteConnection was leake)

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 !

No Empty constructor ? cant seem to figure out.

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

Categories

Resources