[Q]Android Bluetooth - mHandler and manageConnectedSocket errors - Java for Android App Development

Hi! I am beginner in Android programming. I would like to learn how to send a string between 2 devices via Bluetooth. I was trying to write a code on the base of page http://developer.android.com/guide/topics/connectivity/bluetooth.html
I got 3 errors. The first one is, that the MainActivity is underlined red in the following row:
Code:
public class MainActivity extends Activity {
It says: 'The blank final field mHandler may not have been initialized'
The other 2 errors are shown in the AcceptThread and ConnectThread classes. The following row is underlined red:
Code:
manageConnectedSocket(socket);
It says: 'The method manageConnectedSocket(BluetoothSocket) is undefined for the type AcceptThread' and 'The method manageConnectedSocket(BluetoothSocket) is undefined for the type ConnectThread'
Could you please tell me, how to fix the problems and explain me, what were the problems? Thanks in advance.
MainActivity.java:
Code:
package com.example.probax8;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
private final static int REQUEST_ENABLE_BT = 1;
private BluetoothAdapter mBluetoothAdapter = null;
private ArrayAdapter<String> mNewDevicesArrayAdapter;
private final UUID my_UUID = UUID.fromString("00001802-0000-1000-8000-00805f9b34fb");
protected static final int MESSAGE_READ = 1;
BroadcastReceiver mReceiver;
private final Handler mHandler;
private BluetoothSocket socket;
String address;
TextView tv;
int a = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//**** Is BlueTooth and enable BT
final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
// Device does not support Bluetooth
}
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
//**** ON/OFF Bluetooth on click
Button btButton = (Button) findViewById(R.id.bBT);
btButton.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(!mBluetoothAdapter.isEnabled()){
mBluetoothAdapter.enable();
}
else{
mBluetoothAdapter.disable();
}
}
});
//**** make Bluetooth discoverable
Button discButton = (Button) findViewById(R.id.bDis);
discButton.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent discoverableIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
}
});
Button stopDiscButton = (Button) findViewById(R.id.bStopDisc);
stopDiscButton.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mBluetoothAdapter.startDiscovery();
}
});
Button startDiscButton = (Button) findViewById(R.id.bStartDisc);
startDiscButton.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mBluetoothAdapter.startDiscovery();
}
});
tv = (TextView) findViewById(R.id.textView1);
mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// If it's already paired, skip it, because it's been listed already
if (device.getBondState() != BluetoothDevice.BOND_BONDED)
{
mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
tv.setText(device.getName() + "\n" + device.getAddress());
}
}
}
};
//****
mNewDevicesArrayAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,0);
ListView newDevicesListView = (ListView) findViewById(R.id.listView1);
newDevicesListView.setAdapter(mNewDevicesArrayAdapter);
mNewDevicesArrayAdapter.notifyDataSetChanged();
// newDevicesListView.setOnItemClickListener(mDeviceClickListener);
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
// If there are paired devices
if (pairedDevices.size() > 0) {
// Loop through paired devices
for (BluetoothDevice device : pairedDevices) {
// Add the name and address to an array adapter to show in a ListView
mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
}
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(mReceiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(mReceiver, filter);
newDevicesListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
// mBluetoothAdapter.cancelDiscovery();
final String info = ((TextView) arg1).getText().toString();
//get the device address when click the device item
address = info.substring(info.length()-17);
a = 1;
Log.e(TAG, address);
//connect the device when item is click
BluetoothDevice connect_device = mBluetoothAdapter.getRemoteDevice(address);
try {
socket = connect_device.createRfcommSocketToServiceRecord(my_UUID);
socket.connect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});//************new_devices_list end
if(a==1){
Toast.makeText(this, address,Toast.LENGTH_LONG).show();
}
Button unregButton = (Button) findViewById(R.id.bUnreg);
unregButton.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
unregisterReceiver(mReceiver);
}
});
//**************
class AcceptThread extends Thread {
private final BluetoothServerSocket mmServerSocket;
public AcceptThread() {
// Use a temporary object that is later assigned to mmServerSocket,
// because mmServerSocket is final
BluetoothServerSocket tmp = null;
try {
// MY_UUID is the app's UUID string, also used by the client code
tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord("MainActivity", my_UUID);
} catch (IOException e) { }
mmServerSocket = tmp;
}
public void run() {
BluetoothSocket socket = null;
// Keep listening until exception occurs or a socket is returned
while (true) {
try {
socket = mmServerSocket.accept();
} catch (IOException e) {
break;
}
// If a connection was accepted
if (socket != null) {
// Do work to manage the connection (in a separate thread)
manageConnectedSocket(socket);
mmServerSocket.close();
}
}
}
/** Will cancel the listening socket, and cause the thread to finish */
public void cancel() {
try {
mmServerSocket.close();
} catch (IOException e) { }
}
}
//***********
class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = device.createRfcommSocketToServiceRecord(my_UUID);
} catch (IOException e) { }
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the connection
mBluetoothAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
// Do work to manage the connection (in a separate thread)
manageConnectedSocket(mmSocket);
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
//**********
class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI activity
mHandler.obtainMessage(MainActivity.MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
} catch (IOException e) { }
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
}
}
activity_main.xml:
Code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<Button
android:id="@+id/bBT"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView1"
android:text="Bluetooth" />
<Button
android:id="@+id/bDis"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/bBT"
android:text="Disc 300s" />
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/bDis" >
</ListView>
<Button
android:id="@+id/bRetry"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/bBT"
android:layout_alignBottom="@+id/bBT"
android:layout_toRightOf="@+id/bBT"
android:text="Retry" />
<Button
android:id="@+id/bUnreg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/bRetry"
android:layout_toRightOf="@+id/bRetry"
android:text="Unregister" />
<Button
android:id="@+id/bStopDisc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/bRetry"
android:layout_toRightOf="@+id/bDis"
android:text="StopDisc" />
<Button
android:id="@+id/bStartDisc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/bUnreg"
android:layout_toRightOf="@+id/bStopDisc"
android:text="StartDisc" />
</RelativeLayout>

Related

[Q] Item separator in ListView fails! Why?

i have a problem with ListView, i don't view line separator for each item, why ? see where is mouse pointer:
h_t_t_p://tinyurl.com/2vqg52n
and this is source code:
Java Class:
Code:
public class ScienzeInfoNewsActivity extends Activity {
private class Link {
private String title;
private String href;
public Link(String title, String href) {
this.title = title;
this.href = href;
}
public String toString() {
return title;
}
public String getHref() {
return href;
}
}
private FeedReader feedReader;
private ArrayAdapter<Link> adapter;
private ListView list;
public void initialize() {
adapter = new ArrayAdapter<Link>(this, R.layout.textview);
list = (ListView) findViewById(R.id.ListView01);
list.setAdapter(adapter);
}
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initialize();
loadFeeds(adapter);
setAllListener();
}
private void setAllListener() {
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, int position,
long id) {
String link = adapter.getItem((int) id).getHref();
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(link));
startActivity(intent);
}
});
Button exit = (Button) findViewById(R.id.Button02);
exit.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
ScienzeInfoNewsActivity.this.finish();
}
});
Button refresh = (Button) findViewById(R.id.Button01);
refresh.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
loadFeeds(adapter);
}
});
}
private void loadFeeds(ArrayAdapter<Link> adapter) {
if (adapter != null)
adapter.clear();
try {
feedReader = new FeedReader(new URL(
"rss.php"));
String feeds[][] = feedReader.getFeeds();
for (int i = 0; i < feeds.length; i++) {
adapter.add(new Link(feeds[i][0], feeds[i][1]));
}
} catch (Exception e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
R.layout.textview:
Code:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="h_t_t_p://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:textSize="16sp" >
</TextView>
I load entry item with this function loadFeeds()
If i select one of the items without a separator, it just one item.
Thanks for any reply.

Pass Connection Between Intents

I am building an android application to do various queries on my MySQL database. Once a successful login has returned on the main activity, I create a new Intent that holds search and query options. Here's the issue I am having. I keep getting a null pointer exception on stmt = con.createStatement(); Below is my logcat:
Code:
08-20 16:12:07.359 654-810/com.android.exchange D/ExchangeService: !!! deviceId unknown; stopping self and retrying
08-20 16:12:08.469 36-653/? E/SurfaceFlinger: ro.sf.lcd_density must be defined as a build property
08-20 16:12:11.559 1926-1949/com.example.testapplication W/System.err: java.lang.NullPointerException
08-20 16:12:11.559 1926-1949/com.example.testapplication W/System.err: at com.example.testapplication.Networking.Search(Networking.java:44)
08-20 16:12:11.559 1926-1949/com.example.testapplication W/System.err: at com.example.testapplication.ControlActivity$1.run(ControlActivity.java:53)
08-20 16:12:11.559 1926-1949/com.example.testapplication W/System.err: at java.lang.Thread.run(Thread.java:856)
08-20 16:12:12.369 654-654/com.android.exchange D/ExchangeService: !!! EAS ExchangeService, onStartCommand, startingUp = false, running = false
08-20 16:12:12.369 278-498/system_process W/ActivityManager: Unable to start service Intent { act=com.android.email.ACCOUNT_INTENT } U=0: not found
08-20 16:12:12.369 654-815/com.android.exchange D/ExchangeService: !!! Email application not found; stopping self
08-20 16:12:12.379 278-278/system_process W/ActivityManager: Unable to start service Intent { act=com.android.email.ACCOUNT_INTENT } U=0: not found
I'm curious whether it is better practice to close the connection and reopen it in the new intent? Or pass the connection between intents somehow?
Any input would be greatly appreciated!
wait...
Here are snippets of my code to help debug.
Code:
[user=439709]@override[/user]
public void onClick(View view) {
if(view.getId() == R.id.LoginButton) {
Toast.makeText(getApplicationContext(), "Attempting Connection", Toast.LENGTH_SHORT).show();
//Spawn new thread
new Thread(new Runnable() {
public void run() {
if(net.execLogin(mUserInput.getText().toString(), mPassInput.getText().toString())) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Connected to Database", Toast.LENGTH_LONG).show();
}
});
//start new activity
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
[user=439709]@override[/user]
public void run() {
Intent intent = new Intent(LoginActivity.this, ControlActivity.class);
startActivity(intent);
}
});
}
else {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Connection Failed :(", Toast.LENGTH_LONG).show();
}
});
}
}
}).start();
}
}
And here is the new activity started by the above code:
Code:
package com.example.testapplication;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class ControlActivity extends Activity implements View.OnClickListener {
private ArrayList<Hardware> list = new ArrayList<Hardware>();
EditText mEditText;
ListView mListView;
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_control);
setupPage();
}
public void setupPage() {
Button search = (Button)findViewById(R.id.search);
search.setOnClickListener(this);
mEditText = (EditText)findViewById(R.id.editText);
mListView = (ListView)findViewById(R.id.listView);
}
[user=439709]@override[/user]
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.control, menu);
return true;
}
public void onClick(View view) {
if(view.getId() == R.id.search) {
new Thread(new Runnable() {
public void run() {
list = new Networking().Search("Type", mEditText.getText().toString());
}
}).start();
ArrayAdapter<Hardware> adapter = new ArrayAdapter<Hardware>(this, android.R.layout.simple_list_item_1, list);
adapter.notifyDataSetChanged();
mListView.setAdapter(adapter);
if(list == null) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "0 Results Yielded :(", Toast.LENGTH_SHORT).show();
}
});
}
}
}
}
And here is the code I use to connect and query the database
Code:
import java.sql.*;
import java.util.*;
public class Networking implements DbQuery {
private static final String DRIVER = "org.mariadb.jdbc.Driver";
private static final String URL = "jdbc:mysql://146.187.16.32/Peirce";
ArrayList<Hardware> ara = new ArrayList<Hardware>();
Database db = new Database();
Hardware h1;
Connection con = null;
Statement stmt = null;
public boolean execLogin(String uName, String pWord) {
try {
Class.forName(DRIVER);
con = DriverManager.getConnection(URL, uName, pWord);
if(!con.isClosed()){
return true;
}
return false;
}catch(SQLException e) {
e.printStackTrace();
}catch(ClassNotFoundException e) {
e.printStackTrace();
}
return false;
}
public ArrayList<Hardware> Search(String arg, String target) {
try {
stmt = con.createStatement(); //throws null pointer exception
ResultSet rs = stmt.executeQuery("Select * from " + db.getTable() + " where " + arg + "='" + target + "';");
while(rs.next()) {
ara.add(new Hardware(rs.getString("Type"), rs.getString("Make"), rs.getString("Model"), rs.getString("Serial"), rs.getString("Comments")));
}
return ara;
}catch(SQLException e) {
e.printStackTrace();
}catch(NullPointerException e) {
e.printStackTrace();
}
return ara;
}
nevermind
i have figured it out.

[Q] Animation with surfaceview cant capture screenshot

Hello,
I have a project in which an object moves by tapping it on a scrolling background, I can not despite my best efforts to resolve a problem, the screen remains blank after the screenshot
this is my xml
Code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LayoutRoot"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
</RelativeLayout>
java
Code:
public class MainActivity extends Activity {
BallBounces ball;
File imageFile;
public RelativeLayout CamView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CamView =(RelativeLayout) findViewById(R.id.LayoutRoot);
ball = new BallBounces(this);
setContentView(ball);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.Menu:
//newGame();
case R.id.screenshot:
//showHelp();
TakeScreenshot();
// ScreenshotCapture();
Context context=getApplicationContext();
CharSequence text="screenshot";
int duration=Toast.LENGTH_LONG;
Toast toast=Toast.makeText(context, text, duration);
toast.show();
return true;
case R.id.About:
//showHelp();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void TakeScreenshot()
{
Random num = new Random();
int nu=num.nextInt(1000);
CamView.setDrawingCacheEnabled(true);
CamView.buildDrawingCache(true);
Bitmap bmp = Bitmap.createBitmap(CamView.getDrawingCache()); // Here i have null!
CamView.setDrawingCacheEnabled(false); // clear drawing cache
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bmp.compress(CompressFormat.JPEG, 70, bos);
byte[] bitmapdata = bos.toByteArray();
ByteArrayInputStream fis = new ByteArrayInputStream(bitmapdata);
String picId=String.valueOf(nu);
String myfile="Ghost"+picId+".jpeg";
File dir_image = new File(Environment.getExternalStorageDirectory()+File.separator+"ImageTouch");
dir_image.mkdirs();
try {
File tmpFile = new File(dir_image,myfile);
FileOutputStream fos = new FileOutputStream(tmpFile);
byte[] buf = new byte[1024];
int len;
while ((len = fis.read(buf)) > 0)
{
fos.write(buf, 0, len);
}
fis.close();
fos.close();
Toast.makeText(getApplicationContext(),
"Saved",Toast.LENGTH_LONG).show();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
I tried in every way but I can not get out
Someone can give me a hand?
Thanks
The problem is that with a surface view, the getDrawingCache() method always returns null or a black bitmap...
I got it working in my app by creating a new Canvas with the same size as your surface view and then call surfaceView.onDraw(canvas), passing the new one. You can then write it to a file via its bitmap.
And remember, depending on how intense your onDraw method is you may need to do the saving in an Async task.

[Q]Put view over status bar

I want to put a View over the status bar, the code work right, but I get a RunTime Error.
Code:
//Declared in the Activity
WindowManager wm;
LinearLayout ll;
WindowManager.LayoutParams ll_lp;
//Just a sample layout parameters.
ll_lp = new WindowManager.LayoutParams();
ll_lp.format = PixelFormat.TRANSLUCENT;
ll_lp.height = WindowManager.LayoutParams.FILL_PARENT;
ll_lp.width = WindowManager.LayoutParams.FILL_PARENT;
ll_lp.gravity = Gravity.CLIP_HORIZONTAL | Gravity.TOP;
//This one is necessary.
ll_lp.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
//Play around with these two.
ll_lp.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
ll_lp.flags = ll_lp.flags | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
//This is our main layout.
ll = new LinearLayout(LockScreenAppActivity.this);
ll.setBackgroundColor(android.graphics.Color.argb(0, 0, 0, 0));
ll.setHapticFeedbackEnabled(true);
try {
//And finally we add what we created to the screen.
wm.addView(ll, ll_lp);
} catch (Exception e) {
//I GET THE ERROR HERE
Log.e("Error", "Fail");
e.printStackTrace();
e.getMessage();
}
Code:
LOG:
11-29 23:38:38.109: W/System.err(6462): java.lang.NullPointerException
11-29 23:38:38.117: W/System.err(6462): at com.advanced.locker.LockScreenAppActivity.onCreate(LockScreenAppActivity.java:77)
11-29 23:38:38.117: W/System.err(6462): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
11-29 23:38:38.117: W/System.err(6462): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615)
11-29 23:38:38.117: W/System.err(6462): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)
11-29 23:38:38.117: W/System.err(6462): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
11-29 23:38:38.117: W/System.err(6462): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
11-29 23:38:38.125: W/System.err(6462): at android.os.Handler.dispatchMessage(Handler.java:99)
11-29 23:38:38.125: W/System.err(6462): at android.os.Looper.loop(Looper.java:130)
11-29 23:38:38.125: W/System.err(6462): at android.app.ActivityThread.main(ActivityThread.java:3687)
11-29 23:38:38.125: W/System.err(6462): at java.lang.reflect.Method.invokeNative(Native Method)
11-29 23:38:38.125: W/System.err(6462): at java.lang.reflect.Method.invoke(Method.java:507)
11-29 23:38:38.125: W/System.err(6462): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
11-29 23:38:38.125: W/System.err(6462): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
11-29 23:38:38.125: W/System.err(6462): at dalvik.system.NativeStart.main(Native Method)
11-29 23:45:55.953: E/Error(6884): Fail
11-29 23:55:39.070: W/IInputConnectionWrapper(6884): showStatusIcon on inactive InputConnection
11-29 23:55:53.226: E/Error(7053): Fail
Can anybody help me?
Lot's of thank's!
Don't know whether you idea is possible, but please DO NOT code an empty catch part. Something like e.printStackTrace() and e.getMessage() AT LEAST.
Regards
EmptinessFiller said:
Don't know whether you idea is possible, but please DO NOT code an empty catch part. Something like e.printStackTrace() and e.getMessage() AT LEAST.
Regards
Click to expand...
Click to collapse
Is Correct NOW?
Thank's
It might be correct, but senseless, because you never see e.getMessage(). So u could use Log.e(TAG, e.getMessage()).
But by the way, it'd be great if you'd post your log here and before read it.
Regards
EmptinessFiller said:
It might be correct, but senseless, because you never see e.getMessage(). So u could use Log.e(TAG, e.getMessage()).
But by the way, it'd be great if you'd post your log here and before read it.
Regards
Click to expand...
Click to collapse
Now, i think is fine
Come on please, it's easy, but for me no...
Enviado desde mi GT-S5570I usando Tapatalk 2
You define a variable of type WindowManager but you never assign any object to it.
Add this before the try:
Code:
wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
nikwen said:
You define a variable of type WindowManager but you never assign any object to it.
Add this before the try:
Code:
wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Click to expand...
Click to collapse
Lot's of Thank's friend!
Do you think that I put a view over status bar with it??
Enviado desde mi GT-S5570I usando Tapatalk 2
nikwen said:
You define a variable of type WindowManager but you never assign any object to it.
Add this before the try:
Code:
wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Click to expand...
Click to collapse
Your code works fine, but i can get what i want...
I need something like 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"
}
(Red square)
But my view is under the status bar.
Can u help me?
Thank's in advance!
Enviado desde mi GT-S5570I usando Tapatalk 2
DannyGM16 said:
Your code works fine, but i can get what i want...
I need something like this:
(Red square)
But my view is under the status bar.
Can u help me?
Thank's in advance!
Enviado desde mi GT-S5570I usando Tapatalk 2
Click to expand...
Click to collapse
Maybe you can find some hints in the code of the RoundR app which does actually do what you want to achieve: https://github.com/MohammadAdib/Roundr
nikwen said:
Maybe you can find some hints in the code of the RoundR app which does actually do what you want to achieve: https://github.com/MohammadAdib/Roundr
Click to expand...
Click to collapse
I don't find the code that I need, Help me please.
This is the code:
MainActivity.java:
Code:
package mohammad.adib.roundr;
/**
* Copyright 2013 Mohammad Adib
*
* 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.
*/
import wei.mark.standout.StandOutWindow;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
public class MainActivity extends Activity {
/**
* Main Activity that launches the 4 floating windows (corners)
*
* @author Mohammad Adib <[email protected]>
*
* Contributors: Mark Wei
*
*/
ProgressDialog progress;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (!BootReceiver.boot_up || Corner.running) {
Intent i = new Intent(this, SettingsActivity.class);
startActivity(i);
}
if (prefs.getBoolean("enable", true)) {
StandOutWindow.show(this, Corner.class, 0);
StandOutWindow.show(this, Corner.class, 1);
StandOutWindow.show(this, Corner.class, 2);
StandOutWindow.show(this, Corner.class, 3);
}
finish();
}
}
Corner.java:
Code:
package mohammad.adib.roundr;
/**
* Copyright 2013 Mohammad Adib
*
* 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.
*/
import wei.mark.standout.StandOutWindow;
import wei.mark.standout.constants.StandOutFlags;
import wei.mark.standout.ui.Window;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RemoteViews;
public class Corner extends StandOutWindow {
/**
* The individual floating window that sits at one of the corners of the
* screen. Window ID corresponds to which corner this goes to.
*
* @author Mohammad Adib <[email protected]>
*
* Contributors: Mark Wei, Jan Metten
*
*/
public static final String ACTION_SETTINGS = "SETTINGS";
public static final String BCAST_CONFIGCHANGED = "android.intent.action.CONFIGURATION_CHANGED";
public static final int UPDATE_CODE = 2;
public static final int NOTIFICATION_CODE = 3;
public static final int wildcard = 0;
private SharedPreferences prefs;
public static boolean running = false;
@Override
public String getAppName() {
return "RoundR";
}
@Override
public int getAppIcon() {
return R.drawable.notif_icon;
}
@Override
public void createAndAttachView(int corner, FrameLayout frame) {
// Set the image based on window corner
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
ImageView v = (ImageView) inflater.inflate(R.layout.corner, frame, true).findViewById(R.id.iv);
// Top left by default
v.setImageDrawable(getResources().getDrawable(R.drawable.topleft));
switch (corner) {
case 1:
v.setImageDrawable(getResources().getDrawable(R.drawable.topright));
break;
case 2:
v.setImageDrawable(getResources().getDrawable(R.drawable.bottomleft));
break;
case 3:
v.setImageDrawable(getResources().getDrawable(R.drawable.bottomright));
break;
}
}
private int pxFromDp(double dp) {
return (int) (dp * getResources().getDisplayMetrics().density);
}
/**
* Corners: 0 = top left; 1 = top right; 2 = bottom left; 3 = bottom right;
*/
@Override
public StandOutLayoutParams getParams(int corner, Window window) {
prefs = PreferenceManager.getDefaultSharedPreferences(this);
// Check if this corner is enabled
if (prefs.getBoolean("corner" + corner, true)) {
int radius = pxFromDp(prefs.getInt("radius", 20));
// Thanks to Jan Metten for rewriting this based on gravity
switch (corner) {
case 0:
return new StandOutLayoutParams(corner, radius, radius, Gravity.TOP | Gravity.LEFT);
case 1:
return new StandOutLayoutParams(corner, radius, radius, Gravity.TOP | Gravity.RIGHT);
case 2:
return new StandOutLayoutParams(corner, radius, radius, Gravity.BOTTOM | Gravity.LEFT);
case 3:
return new StandOutLayoutParams(corner, radius, radius, Gravity.BOTTOM | Gravity.RIGHT);
}
}
// Outside of screen
return new StandOutLayoutParams(corner, 1, 1, -1, -1, 1, 1);
}
@Override
public int getFlags(int corner) {
return super.getFlags(corner) | StandOutFlags.FLAG_WINDOW_FOCUSABLE_DISABLE | StandOutFlags.FLAG_WINDOW_EDGE_LIMITS_ENABLE;
}
@Override
public String getPersistentNotificationMessage(int corner) {
return "Tap to configure";
}
@Override
public Intent getPersistentNotificationIntent(int corner) {
return new Intent(this, Corner.class).putExtra("id", corner).setAction(ACTION_SETTINGS);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null) {
String action = intent.getAction();
int corner = intent.getIntExtra("id", DEFAULT_ID);
if (corner == ONGOING_NOTIFICATION_ID) {
throw new RuntimeException("ID cannot equals StandOutWindow.ONGOING_NOTIFICATION_ID");
}
if (ACTION_SHOW.equals(action) || ACTION_RESTORE.equals(action)) {
show(corner);
} else if (ACTION_SETTINGS.equals(action)) {
try {
Intent intentS = new Intent(this, SettingsActivity.class);
intentS.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intentS);
} catch (Exception e) {
// Addressing this issue: http://i.imgur.com/Op9kfy8.png
}
} else if (ACTION_HIDE.equals(action)) {
hide(corner);
} else if (ACTION_CLOSE.equals(action)) {
close(corner);
} else if (ACTION_CLOSE_ALL.equals(action)) {
closeAll();
} else if (ACTION_SEND_DATA.equals(action)) {
if (isExistingId(corner) || corner == DISREGARD_ID) {
Bundle data = intent.getBundleExtra("wei.mark.standout.data");
int requestCode = intent.getIntExtra("requestCode", 0);
@SuppressWarnings("unchecked")
Class<? extends StandOutWindow> fromCls = (Class<? extends StandOutWindow>) intent.getSerializableExtra("wei.mark.standout.fromCls");
int fromId = intent.getIntExtra("fromId", DEFAULT_ID);
onReceiveData(corner, requestCode, data, fromCls, fromId);
}
}
}
return START_NOT_STICKY;
}
@Override
public boolean onClose(final int corner, final Window window) {
running = false;
return false;
}
@Override
public String getPersistentNotificationTitle(int corner) {
return "Rounded Corners";
}
@SuppressLint({ "InlinedApi", "NewApi" })
@SuppressWarnings("deprecation")
@Override
public Notification getPersistentNotification(int id) {
int icon = getAppIcon();
long when = System.currentTimeMillis();
Context c = getApplicationContext();
String contentTitle = getPersistentNotificationTitle(id);
String contentText = getPersistentNotificationMessage(id);
Intent notificationIntent = getPersistentNotificationIntent(id);
PendingIntent contentIntent = PendingIntent.getService(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
// 4.1+ Low priority notification
final int apiLevel = Build.VERSION.SDK_INT;
if (apiLevel >= 16) {
Notification.Builder mBuilder = new Notification.Builder(this).setContent(new RemoteViews(getPackageName(), R.layout.notification)).setSmallIcon(getAppIcon()).setContentTitle(contentTitle).setContentText(contentText).setPriority(Notification.PRIORITY_MIN).setContentIntent(contentIntent);
return mBuilder.build();
}
String tickerText = String.format("%s: %s", contentTitle, contentText);
Notification notification = new Notification(icon, tickerText, when);
notification.setLatestEventInfo(c, contentTitle, contentText, contentIntent);
return notification;
}
@Override
public boolean onShow(final int corner, final Window window) {
running = true;
return false;
}
@Override
public void onReceiveData(int corner, int requestCode, Bundle data, Class<? extends StandOutWindow> fromCls, int fromId) {
Window window = getWindow(corner);
if (requestCode == UPDATE_CODE) {
// Update the corners when device is rotated
updateViewLayout(3, getParams(3, window));
updateViewLayout(2, getParams(2, window));
updateViewLayout(1, getParams(1, window));
updateViewLayout(0, getParams(0, window));
} else if (requestCode == NOTIFICATION_CODE) {
if (!prefs.getBoolean("notification", true)) {
// Hide Notification Icon (for <= Gingerbread devices only)
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = getPersistentNotification(corner);
notification.icon = wei.mark.standout.R.drawable.nothing;
mNotificationManager.notify(getClass().hashCode() + ONGOING_NOTIFICATION_ID, notification);
Log.d("Hello World", "");
} else {
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = getPersistentNotification(corner);
mNotificationManager.notify(getClass().hashCode() + ONGOING_NOTIFICATION_ID, notification);
}
}
}
}
SeekBarPreference:
Code:
package mohammad.adib.roundr;
import wei.mark.standout.StandOutWindow;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.preference.Preference;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
public class SeekBarPreference extends Preference implements OnSeekBarChangeListener {
private final String TAG = getClass().getName();
private static final String ANDROIDNS = "http://schemas.android.com/apk/res/android";
private static final String ROUNDRNS = "roundrprefs";
private static final int DEFAULT_VALUE = 50;
private int mMaxValue = 100;
private int mMinValue = 0;
private int mInterval = 1;
private int mCurrentValue;
private String mUnitsLeft = "";
private String mUnitsRight = "";
private SeekBar mSeekBar;
private Context context;
private TextView mStatusText;
public SeekBarPreference(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
initPreference(context, attrs);
}
public SeekBarPreference(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initPreference(context, attrs);
}
private void initPreference(Context context, AttributeSet attrs) {
setValuesFromXml(attrs);
mSeekBar = new SeekBar(context, attrs);
mSeekBar.setMax(mMaxValue - mMinValue);
mSeekBar.setOnSeekBarChangeListener(this);
}
private void setValuesFromXml(AttributeSet attrs) {
mMaxValue = attrs.getAttributeIntValue(ANDROIDNS, "max", 100);
mMinValue = attrs.getAttributeIntValue(ROUNDRNS, "min", 0);
mUnitsLeft = getAttributeStringValue(attrs, ROUNDRNS, "unitsLeft", "");
String units = getAttributeStringValue(attrs, ROUNDRNS, "units", "");
mUnitsRight = getAttributeStringValue(attrs, ROUNDRNS, "unitsRight", units);
try {
String newInterval = attrs.getAttributeValue(ROUNDRNS, "interval");
if (newInterval != null)
mInterval = Integer.parseInt(newInterval);
} catch (Exception e) {
Log.e(TAG, "Invalid interval value", e);
}
}
private String getAttributeStringValue(AttributeSet attrs, String namespace, String name, String defaultValue) {
String value = attrs.getAttributeValue(namespace, name);
if (value == null)
value = defaultValue;
return value;
}
@Override
protected View onCreateView(ViewGroup parent) {
RelativeLayout layout = null;
try {
LayoutInflater mInflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
layout = (RelativeLayout) mInflater.inflate(R.layout.seek_bar_preference, parent, false);
} catch (Exception e) {
Log.e(TAG, "Error creating seek bar preference", e);
}
return layout;
}
@Override
public void onBindView(View view) {
super.onBindView(view);
try {
// move our seekbar to the new view we've been given
ViewParent oldContainer = mSeekBar.getParent();
ViewGroup newContainer = (ViewGroup) view.findViewById(R.id.seekBarPrefBarContainer);
if (oldContainer != newContainer) {
// remove the seekbar from the old view
if (oldContainer != null) {
((ViewGroup) oldContainer).removeView(mSeekBar);
}
// remove the existing seekbar (there may not be one) and add
// ours
newContainer.removeAllViews();
newContainer.addView(mSeekBar, ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
}
} catch (Exception ex) {
Log.e(TAG, "Error binding view: " + ex.toString());
}
updateView(view);
}
/**
* Update a SeekBarPreference view with our current state
*
* @param view
*/
protected void updateView(View view) {
try {
RelativeLayout layout = (RelativeLayout) view;
mStatusText = (TextView) layout.findViewById(R.id.seekBarPrefValue);
mStatusText.setText(String.valueOf(pxFromDp(mCurrentValue)));
mStatusText.setMinimumWidth(30);
mSeekBar.setProgress(mCurrentValue - mMinValue);
} catch (Exception e) {
Log.e(TAG, "Error updating seek bar preference", e);
}
}
private int pxFromDp(double dp) {
return (int) (dp * context.getResources().getDisplayMetrics().density);
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
int newValue = progress + mMinValue;
if (newValue > mMaxValue)
newValue = mMaxValue;
else if (newValue < mMinValue)
newValue = mMinValue;
else if (mInterval != 1 && newValue % mInterval != 0)
newValue = Math.round(((float) newValue) / mInterval) * mInterval;
// change rejected, revert to the previous value
if (!callChangeListener(newValue)) {
seekBar.setProgress(mCurrentValue - mMinValue);
return;
}
// change accepted, store it
mCurrentValue = newValue;
mStatusText.setText(String.valueOf(pxFromDp(newValue)));
persistInt(newValue);
// Refresh the corners to apply the new radius
StandOutWindow.sendData(context, Corner.class, Corner.wildcard, Corner.UPDATE_CODE, new Bundle(), Corner.class, StandOutWindow.DISREGARD_ID);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
notifyChanged();
}
@Override
protected Object onGetDefaultValue(TypedArray ta, int index) {
int defaultValue = ta.getInt(index, DEFAULT_VALUE);
return defaultValue;
}
@Override
protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
if (restoreValue) {
mCurrentValue = getPersistedInt(mCurrentValue);
} else {
int temp = 0;
try {
temp = (Integer) defaultValue;
} catch (Exception ex) {
Log.e(TAG, "Invalid default value: " + defaultValue.toString());
}
persistInt(temp);
mCurrentValue = temp;
}
}
}
SettingsActivity.java:
Code:
package mohammad.adib.roundr;
import wei.mark.standout.StandOutWindow;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceManager;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.util.Log;
import android.view.WindowManager.LayoutParams;
public class SettingsActivity extends PreferenceActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
/**
* Handle Preference Changes
*/
// Enable/Disable
((Preference) findPreference("enable")).setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
boolean isChecked = (Boolean) newValue;
if (isChecked) {
StandOutWindow.show(SettingsActivity.this, Corner.class, 0);
StandOutWindow.show(SettingsActivity.this, Corner.class, 1);
StandOutWindow.show(SettingsActivity.this, Corner.class, 2);
StandOutWindow.show(SettingsActivity.this, Corner.class, 3);
} else {
StandOutWindow.closeAll(SettingsActivity.this, Corner.class);
}
return true;
}
});
// Notification
final int apiLevel = Build.VERSION.SDK_INT;
if (apiLevel >= 16) {
((Preference) findPreference("notification")).setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
new AlertDialog.Builder(SettingsActivity.this).setTitle("Notification").setMessage("The notification prevents Android from killing RoundR in low memory situations.\n\nOn Android 4.1+ devices, it can be disabled via the App Info.").setPositiveButton("Continue", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
showInstalledAppDetails("mohammad.adib.roundr");
}
}).show();
return true;
}
});
}else{
((Preference) findPreference("notification")).setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
StandOutWindow.sendData(SettingsActivity.this, Corner.class, Corner.wildcard, Corner.NOTIFICATION_CODE, new Bundle(), Corner.class, StandOutWindow.DISREGARD_ID);
return true;
}
});
}
// Enable specific corners
for (int i = 0; i < 4; i++) {
((Preference) findPreference("corner" + i)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
refresh();
return true;
}
});
}
/**
* Overlap Settings TODO: These are messy
*/
((Preference) findPreference("overlap1")).setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
boolean isChecked = (Boolean) newValue;
if (isChecked) {
prefs.edit().putInt("type", LayoutParams.TYPE_SYSTEM_OVERLAY).commit();
if (prefs.getBoolean("overlap2", false))
prefs.edit().putInt("flags", LayoutParams.FLAG_SHOW_WHEN_LOCKED | LayoutParams.FLAG_LAYOUT_IN_SCREEN).commit();
else
prefs.edit().putInt("flags", LayoutParams.FLAG_SHOW_WHEN_LOCKED).commit();
} else {
prefs.edit().putInt("type", LayoutParams.TYPE_SYSTEM_ALERT).commit();
if (prefs.getBoolean("overlap2", false))
prefs.edit().putInt("flags", LayoutParams.FLAG_NOT_TOUCH_MODAL | LayoutParams.FLAG_LAYOUT_IN_SCREEN).commit();
else
prefs.edit().putInt("flags", LayoutParams.FLAG_NOT_TOUCH_MODAL).commit();
}
new Thread(new Runnable() {
@Override
public void run() {
// Disable and Re-enable the corners
StandOutWindow.closeAll(SettingsActivity.this, Corner.class);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
StandOutWindow.show(SettingsActivity.this, Corner.class, 0);
StandOutWindow.show(SettingsActivity.this, Corner.class, 1);
StandOutWindow.show(SettingsActivity.this, Corner.class, 2);
StandOutWindow.show(SettingsActivity.this, Corner.class, 3);
}
}).start();
return true;
}
});
((Preference) findPreference("overlap2")).setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
boolean isChecked = (Boolean) newValue;
if (isChecked) {
if (prefs.getBoolean("overlap", true))
prefs.edit().putInt("flags", LayoutParams.FLAG_SHOW_WHEN_LOCKED | LayoutParams.FLAG_LAYOUT_IN_SCREEN).commit();
else
prefs.edit().putInt("flags", LayoutParams.FLAG_NOT_TOUCH_MODAL | LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH | LayoutParams.FLAG_LAYOUT_IN_SCREEN).commit();
} else {
if (prefs.getBoolean("overlap", true))
prefs.edit().putInt("flags", LayoutParams.FLAG_SHOW_WHEN_LOCKED).commit();
else
prefs.edit().putInt("flags", LayoutParams.FLAG_NOT_TOUCH_MODAL | LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH).commit();
}
new Thread(new Runnable() {
@Override
public void run() {
// Disable and Reenable the corners
StandOutWindow.closeAll(SettingsActivity.this, Corner.class);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
StandOutWindow.show(SettingsActivity.this, Corner.class, 0);
StandOutWindow.show(SettingsActivity.this, Corner.class, 1);
StandOutWindow.show(SettingsActivity.this, Corner.class, 2);
StandOutWindow.show(SettingsActivity.this, Corner.class, 3);
}
}).start();
return true;
}
});
/**
* TODO: Figure out if Developer Options is enabled. If so, show a
* GitHub Source Code Link preference:
* "Seems like you are a developer? Check out the RoundR source code on GitHub!"
*/
}
/*
* Sends a signal to all the corners to refresh their layout parameters,
* which in turn refreshes their size.
*/
public void refresh() {
StandOutWindow.sendData(this, Corner.class, Corner.wildcard, Corner.UPDATE_CODE, new Bundle(), Corner.class, StandOutWindow.DISREGARD_ID);
}
@SuppressLint("InlinedApi")
public void showInstalledAppDetails(String packageName) {
Intent intent = new Intent();
intent.setAction(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", packageName, null);
intent.setData(uri);
startActivity(intent);
}
}
preferences.xml:
Code:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:roundr="roundrprefs" >
<PreferenceCategory android:title="General Settings" >
<CheckBoxPreference
android:defaultValue="true"
android:key="enable"
android:summary="Enable rounded screen corners"
android:title="Enable RoundR" />
<CheckBoxPreference
android:defaultValue="true"
android:key="start_on_boot"
android:summary="Start RoundR automatically on boot"
android:title="Start on boot" />
<CheckBoxPreference
android:defaultValue="true"
android:key="notification"
android:summary="The notification is required to keep RoundR running in low memory situations"
android:title="Visible Notification" />
</PreferenceCategory>
<PreferenceCategory android:title="RoundR Settings" >
<PreferenceScreen
android:dependency="enable"
android:persistent="false"
android:summary="Enable rounding on specific corners"
android:title="Enabled Corners" >
<CheckBoxPreference
android:defaultValue="true"
android:key="corner0"
android:title="Top Left" />
<CheckBoxPreference
android:defaultValue="true"
android:key="corner1"
android:title="Top Right" />
<CheckBoxPreference
android:defaultValue="true"
android:key="corner2"
android:title="Bottom Left" />
<CheckBoxPreference
android:defaultValue="true"
android:key="corner3"
android:title="Bottom Right" />
</PreferenceScreen>
<mohammad.adib.roundr.SeekBarPreference
android:defaultValue="10"
android:key="radius"
android:max="40"
android:title="Corner Radius"
roundr:min="2"
roundr:unitsLeft=""
roundr:unitsRight="" />
<CheckBoxPreference
android:defaultValue="true"
android:key="overlap1"
android:summary="This also constitutes overlaping of the corners on the notification pull-down"
android:title="Enable on lockscreen" />
<CheckBoxPreference
android:defaultValue="false"
android:key="overlap2"
android:summary="Allows for the corners to overlap the status bar"
android:title="Overlap Status Bar" />
</PreferenceCategory>
</PreferenceScreen>
Can u help me? where is the specific code that i need, i was trying to find it for hours...
Enviado desde mi GT-S5570I usando Tapatalk 2
DannyGM16 said:
I don't find the code that I need, Help me please.
This is the code:
MainActivity.java:
Code:
package mohammad.adib.roundr;
/**
* Copyright 2013 Mohammad Adib
*
* 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.
*/
import wei.mark.standout.StandOutWindow;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
public class MainActivity extends Activity {
/**
* Main Activity that launches the 4 floating windows (corners)
*
* @author Mohammad Adib <[email protected]>
*
* Contributors: Mark Wei
*
*/
ProgressDialog progress;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (!BootReceiver.boot_up || Corner.running) {
Intent i = new Intent(this, SettingsActivity.class);
startActivity(i);
}
if (prefs.getBoolean("enable", true)) {
StandOutWindow.show(this, Corner.class, 0);
StandOutWindow.show(this, Corner.class, 1);
StandOutWindow.show(this, Corner.class, 2);
StandOutWindow.show(this, Corner.class, 3);
}
finish();
}
}
Corner.java:
Code:
package mohammad.adib.roundr;
/**
* Copyright 2013 Mohammad Adib
*
* 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.
*/
import wei.mark.standout.StandOutWindow;
import wei.mark.standout.constants.StandOutFlags;
import wei.mark.standout.ui.Window;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RemoteViews;
public class Corner extends StandOutWindow {
/**
* The individual floating window that sits at one of the corners of the
* screen. Window ID corresponds to which corner this goes to.
*
* @author Mohammad Adib <[email protected]>
*
* Contributors: Mark Wei, Jan Metten
*
*/
public static final String ACTION_SETTINGS = "SETTINGS";
public static final String BCAST_CONFIGCHANGED = "android.intent.action.CONFIGURATION_CHANGED";
public static final int UPDATE_CODE = 2;
public static final int NOTIFICATION_CODE = 3;
public static final int wildcard = 0;
private SharedPreferences prefs;
public static boolean running = false;
@Override
public String getAppName() {
return "RoundR";
}
@Override
public int getAppIcon() {
return R.drawable.notif_icon;
}
@Override
public void createAndAttachView(int corner, FrameLayout frame) {
// Set the image based on window corner
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
ImageView v = (ImageView) inflater.inflate(R.layout.corner, frame, true).findViewById(R.id.iv);
// Top left by default
v.setImageDrawable(getResources().getDrawable(R.drawable.topleft));
switch (corner) {
case 1:
v.setImageDrawable(getResources().getDrawable(R.drawable.topright));
break;
case 2:
v.setImageDrawable(getResources().getDrawable(R.drawable.bottomleft));
break;
case 3:
v.setImageDrawable(getResources().getDrawable(R.drawable.bottomright));
break;
}
}
private int pxFromDp(double dp) {
return (int) (dp * getResources().getDisplayMetrics().density);
}
/**
* Corners: 0 = top left; 1 = top right; 2 = bottom left; 3 = bottom right;
*/
@Override
public StandOutLayoutParams getParams(int corner, Window window) {
prefs = PreferenceManager.getDefaultSharedPreferences(this);
// Check if this corner is enabled
if (prefs.getBoolean("corner" + corner, true)) {
int radius = pxFromDp(prefs.getInt("radius", 20));
// Thanks to Jan Metten for rewriting this based on gravity
switch (corner) {
case 0:
return new StandOutLayoutParams(corner, radius, radius, Gravity.TOP | Gravity.LEFT);
case 1:
return new StandOutLayoutParams(corner, radius, radius, Gravity.TOP | Gravity.RIGHT);
case 2:
return new StandOutLayoutParams(corner, radius, radius, Gravity.BOTTOM | Gravity.LEFT);
case 3:
return new StandOutLayoutParams(corner, radius, radius, Gravity.BOTTOM | Gravity.RIGHT);
}
}
// Outside of screen
return new StandOutLayoutParams(corner, 1, 1, -1, -1, 1, 1);
}
@Override
public int getFlags(int corner) {
return super.getFlags(corner) | StandOutFlags.FLAG_WINDOW_FOCUSABLE_DISABLE | StandOutFlags.FLAG_WINDOW_EDGE_LIMITS_ENABLE;
}
@Override
public String getPersistentNotificationMessage(int corner) {
return "Tap to configure";
}
@Override
public Intent getPersistentNotificationIntent(int corner) {
return new Intent(this, Corner.class).putExtra("id", corner).setAction(ACTION_SETTINGS);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null) {
String action = intent.getAction();
int corner = intent.getIntExtra("id", DEFAULT_ID);
if (corner == ONGOING_NOTIFICATION_ID) {
throw new RuntimeException("ID cannot equals StandOutWindow.ONGOING_NOTIFICATION_ID");
}
if (ACTION_SHOW.equals(action) || ACTION_RESTORE.equals(action)) {
show(corner);
} else if (ACTION_SETTINGS.equals(action)) {
try {
Intent intentS = new Intent(this, SettingsActivity.class);
intentS.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intentS);
} catch (Exception e) {
// Addressing this issue: http://i.imgur.com/Op9kfy8.png
}
} else if (ACTION_HIDE.equals(action)) {
hide(corner);
} else if (ACTION_CLOSE.equals(action)) {
close(corner);
} else if (ACTION_CLOSE_ALL.equals(action)) {
closeAll();
} else if (ACTION_SEND_DATA.equals(action)) {
if (isExistingId(corner) || corner == DISREGARD_ID) {
Bundle data = intent.getBundleExtra("wei.mark.standout.data");
int requestCode = intent.getIntExtra("requestCode", 0);
@SuppressWarnings("unchecked")
Class<? extends StandOutWindow> fromCls = (Class<? extends StandOutWindow>) intent.getSerializableExtra("wei.mark.standout.fromCls");
int fromId = intent.getIntExtra("fromId", DEFAULT_ID);
onReceiveData(corner, requestCode, data, fromCls, fromId);
}
}
}
return START_NOT_STICKY;
}
@Override
public boolean onClose(final int corner, final Window window) {
running = false;
return false;
}
@Override
public String getPersistentNotificationTitle(int corner) {
return "Rounded Corners";
}
@SuppressLint({ "InlinedApi", "NewApi" })
@SuppressWarnings("deprecation")
@Override
public Notification getPersistentNotification(int id) {
int icon = getAppIcon();
long when = System.currentTimeMillis();
Context c = getApplicationContext();
String contentTitle = getPersistentNotificationTitle(id);
String contentText = getPersistentNotificationMessage(id);
Intent notificationIntent = getPersistentNotificationIntent(id);
PendingIntent contentIntent = PendingIntent.getService(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
// 4.1+ Low priority notification
final int apiLevel = Build.VERSION.SDK_INT;
if (apiLevel >= 16) {
Notification.Builder mBuilder = new Notification.Builder(this).setContent(new RemoteViews(getPackageName(), R.layout.notification)).setSmallIcon(getAppIcon()).setContentTitle(contentTitle).setContentText(contentText).setPriority(Notification.PRIORITY_MIN).setContentIntent(contentIntent);
return mBuilder.build();
}
String tickerText = String.format("%s: %s", contentTitle, contentText);
Notification notification = new Notification(icon, tickerText, when);
notification.setLatestEventInfo(c, contentTitle, contentText, contentIntent);
return notification;
}
@Override
public boolean onShow(final int corner, final Window window) {
running = true;
return false;
}
@Override
public void onReceiveData(int corner, int requestCode, Bundle data, Class<? extends StandOutWindow> fromCls, int fromId) {
Window window = getWindow(corner);
if (requestCode == UPDATE_CODE) {
// Update the corners when device is rotated
updateViewLayout(3, getParams(3, window));
updateViewLayout(2, getParams(2, window));
updateViewLayout(1, getParams(1, window));
updateViewLayout(0, getParams(0, window));
} else if (requestCode == NOTIFICATION_CODE) {
if (!prefs.getBoolean("notification", true)) {
// Hide Notification Icon (for <= Gingerbread devices only)
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = getPersistentNotification(corner);
notification.icon = wei.mark.standout.R.drawable.nothing;
mNotificationManager.notify(getClass().hashCode() + ONGOING_NOTIFICATION_ID, notification);
Log.d("Hello World", "");
} else {
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = getPersistentNotification(corner);
mNotificationManager.notify(getClass().hashCode() + ONGOING_NOTIFICATION_ID, notification);
}
}
}
}
SeekBarPreference:
Code:
package mohammad.adib.roundr;
import wei.mark.standout.StandOutWindow;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.preference.Preference;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
public class SeekBarPreference extends Preference implements OnSeekBarChangeListener {
private final String TAG = getClass().getName();
private static final String ANDROIDNS = "http://schemas.android.com/apk/res/android";
private static final String ROUNDRNS = "roundrprefs";
private static final int DEFAULT_VALUE = 50;
private int mMaxValue = 100;
private int mMinValue = 0;
private int mInterval = 1;
private int mCurrentValue;
private String mUnitsLeft = "";
private String mUnitsRight = "";
private SeekBar mSeekBar;
private Context context;
private TextView mStatusText;
public SeekBarPreference(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
initPreference(context, attrs);
}
public SeekBarPreference(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initPreference(context, attrs);
}
private void initPreference(Context context, AttributeSet attrs) {
setValuesFromXml(attrs);
mSeekBar = new SeekBar(context, attrs);
mSeekBar.setMax(mMaxValue - mMinValue);
mSeekBar.setOnSeekBarChangeListener(this);
}
private void setValuesFromXml(AttributeSet attrs) {
mMaxValue = attrs.getAttributeIntValue(ANDROIDNS, "max", 100);
mMinValue = attrs.getAttributeIntValue(ROUNDRNS, "min", 0);
mUnitsLeft = getAttributeStringValue(attrs, ROUNDRNS, "unitsLeft", "");
String units = getAttributeStringValue(attrs, ROUNDRNS, "units", "");
mUnitsRight = getAttributeStringValue(attrs, ROUNDRNS, "unitsRight", units);
try {
String newInterval = attrs.getAttributeValue(ROUNDRNS, "interval");
if (newInterval != null)
mInterval = Integer.parseInt(newInterval);
} catch (Exception e) {
Log.e(TAG, "Invalid interval value", e);
}
}
private String getAttributeStringValue(AttributeSet attrs, String namespace, String name, String defaultValue) {
String value = attrs.getAttributeValue(namespace, name);
if (value == null)
value = defaultValue;
return value;
}
@Override
protected View onCreateView(ViewGroup parent) {
RelativeLayout layout = null;
try {
LayoutInflater mInflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
layout = (RelativeLayout) mInflater.inflate(R.layout.seek_bar_preference, parent, false);
} catch (Exception e) {
Log.e(TAG, "Error creating seek bar preference", e);
}
return layout;
}
@Override
public void onBindView(View view) {
super.onBindView(view);
try {
// move our seekbar to the new view we've been given
ViewParent oldContainer = mSeekBar.getParent();
ViewGroup newContainer = (ViewGroup) view.findViewById(R.id.seekBarPrefBarContainer);
if (oldContainer != newContainer) {
// remove the seekbar from the old view
if (oldContainer != null) {
((ViewGroup) oldContainer).removeView(mSeekBar);
}
// remove the existing seekbar (there may not be one) and add
// ours
newContainer.removeAllViews();
newContainer.addView(mSeekBar, ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
}
} catch (Exception ex) {
Log.e(TAG, "Error binding view: " + ex.toString());
}
updateView(view);
}
/**
* Update a SeekBarPreference view with our current state
*
* @param view
*/
protected void updateView(View view) {
try {
RelativeLayout layout = (RelativeLayout) view;
mStatusText = (TextView) layout.findViewById(R.id.seekBarPrefValue);
mStatusText.setText(String.valueOf(pxFromDp(mCurrentValue)));
mStatusText.setMinimumWidth(30);
mSeekBar.setProgress(mCurrentValue - mMinValue);
} catch (Exception e) {
Log.e(TAG, "Error updating seek bar preference", e);
}
}
private int pxFromDp(double dp) {
return (int) (dp * context.getResources().getDisplayMetrics().density);
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
int newValue = progress + mMinValue;
if (newValue > mMaxValue)
newValue = mMaxValue;
else if (newValue < mMinValue)
newValue = mMinValue;
else if (mInterval != 1 && newValue % mInterval != 0)
newValue = Math.round(((float) newValue) / mInterval) * mInterval;
// change rejected, revert to the previous value
if (!callChangeListener(newValue)) {
seekBar.setProgress(mCurrentValue - mMinValue);
return;
}
// change accepted, store it
mCurrentValue = newValue;
mStatusText.setText(String.valueOf(pxFromDp(newValue)));
persistInt(newValue);
// Refresh the corners to apply the new radius
StandOutWindow.sendData(context, Corner.class, Corner.wildcard, Corner.UPDATE_CODE, new Bundle(), Corner.class, StandOutWindow.DISREGARD_ID);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
notifyChanged();
}
@Override
protected Object onGetDefaultValue(TypedArray ta, int index) {
int defaultValue = ta.getInt(index, DEFAULT_VALUE);
return defaultValue;
}
@Override
protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
if (restoreValue) {
mCurrentValue = getPersistedInt(mCurrentValue);
} else {
int temp = 0;
try {
temp = (Integer) defaultValue;
} catch (Exception ex) {
Log.e(TAG, "Invalid default value: " + defaultValue.toString());
}
persistInt(temp);
mCurrentValue = temp;
}
}
}
SettingsActivity.java:
Code:
package mohammad.adib.roundr;
import wei.mark.standout.StandOutWindow;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceManager;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.util.Log;
import android.view.WindowManager.LayoutParams;
public class SettingsActivity extends PreferenceActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
/**
* Handle Preference Changes
*/
// Enable/Disable
((Preference) findPreference("enable")).setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
boolean isChecked = (Boolean) newValue;
if (isChecked) {
StandOutWindow.show(SettingsActivity.this, Corner.class, 0);
StandOutWindow.show(SettingsActivity.this, Corner.class, 1);
StandOutWindow.show(SettingsActivity.this, Corner.class, 2);
StandOutWindow.show(SettingsActivity.this, Corner.class, 3);
} else {
StandOutWindow.closeAll(SettingsActivity.this, Corner.class);
}
return true;
}
});
// Notification
final int apiLevel = Build.VERSION.SDK_INT;
if (apiLevel >= 16) {
((Preference) findPreference("notification")).setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
new AlertDialog.Builder(SettingsActivity.this).setTitle("Notification").setMessage("The notification prevents Android from killing RoundR in low memory situations.\n\nOn Android 4.1+ devices, it can be disabled via the App Info.").setPositiveButton("Continue", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
showInstalledAppDetails("mohammad.adib.roundr");
}
}).show();
return true;
}
});
}else{
((Preference) findPreference("notification")).setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
StandOutWindow.sendData(SettingsActivity.this, Corner.class, Corner.wildcard, Corner.NOTIFICATION_CODE, new Bundle(), Corner.class, StandOutWindow.DISREGARD_ID);
return true;
}
});
}
// Enable specific corners
for (int i = 0; i < 4; i++) {
((Preference) findPreference("corner" + i)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
refresh();
return true;
}
});
}
/**
* Overlap Settings TODO: These are messy
*/
((Preference) findPreference("overlap1")).setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
boolean isChecked = (Boolean) newValue;
if (isChecked) {
prefs.edit().putInt("type", LayoutParams.TYPE_SYSTEM_OVERLAY).commit();
if (prefs.getBoolean("overlap2", false))
prefs.edit().putInt("flags", LayoutParams.FLAG_SHOW_WHEN_LOCKED | LayoutParams.FLAG_LAYOUT_IN_SCREEN).commit();
else
prefs.edit().putInt("flags", LayoutParams.FLAG_SHOW_WHEN_LOCKED).commit();
} else {
prefs.edit().putInt("type", LayoutParams.TYPE_SYSTEM_ALERT).commit();
if (prefs.getBoolean("overlap2", false))
prefs.edit().putInt("flags", LayoutParams.FLAG_NOT_TOUCH_MODAL | LayoutParams.FLAG_LAYOUT_IN_SCREEN).commit();
else
prefs.edit().putInt("flags", LayoutParams.FLAG_NOT_TOUCH_MODAL).commit();
}
new Thread(new Runnable() {
@Override
public void run() {
// Disable and Re-enable the corners
StandOutWindow.closeAll(SettingsActivity.this, Corner.class);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
StandOutWindow.show(SettingsActivity.this, Corner.class, 0);
StandOutWindow.show(SettingsActivity.this, Corner.class, 1);
StandOutWindow.show(SettingsActivity.this, Corner.class, 2);
StandOutWindow.show(SettingsActivity.this, Corner.class, 3);
}
}).start();
return true;
}
});
((Preference) findPreference("overlap2")).setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
boolean isChecked = (Boolean) newValue;
if (isChecked) {
if (prefs.getBoolean("overlap", true))
prefs.edit().putInt("flags", LayoutParams.FLAG_SHOW_WHEN_LOCKED | LayoutParams.FLAG_LAYOUT_IN_SCREEN).commit();
else
prefs.edit().putInt("flags", LayoutParams.FLAG_NOT_TOUCH_MODAL | LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH | LayoutParams.FLAG_LAYOUT_IN_SCREEN).commit();
} else {
if (prefs.getBoolean("overlap", true))
prefs.edit().putInt("flags", LayoutParams.FLAG_SHOW_WHEN_LOCKED).commit();
else
prefs.edit().putInt("flags", LayoutParams.FLAG_NOT_TOUCH_MODAL | LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH).commit();
}
new Thread(new Runnable() {
@Override
public void run() {
// Disable and Reenable the corners
StandOutWindow.closeAll(SettingsActivity.this, Corner.class);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
StandOutWindow.show(SettingsActivity.this, Corner.class, 0);
StandOutWindow.show(SettingsActivity.this, Corner.class, 1);
StandOutWindow.show(SettingsActivity.this, Corner.class, 2);
StandOutWindow.show(SettingsActivity.this, Corner.class, 3);
}
}).start();
return true;
}
});
/**
* TODO: Figure out if Developer Options is enabled. If so, show a
* GitHub Source Code Link preference:
* "Seems like you are a developer? Check out the RoundR source code on GitHub!"
*/
}
/*
* Sends a signal to all the corners to refresh their layout parameters,
* which in turn refreshes their size.
*/
public void refresh() {
StandOutWindow.sendData(this, Corner.class, Corner.wildcard, Corner.UPDATE_CODE, new Bundle(), Corner.class, StandOutWindow.DISREGARD_ID);
}
@SuppressLint("InlinedApi")
public void showInstalledAppDetails(String packageName) {
Intent intent = new Intent();
intent.setAction(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", packageName, null);
intent.setData(uri);
startActivity(intent);
}
}
preferences.xml:
Code:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:roundr="roundrprefs" >
<PreferenceCategory android:title="General Settings" >
<CheckBoxPreference
android:defaultValue="true"
android:key="enable"
android:summary="Enable rounded screen corners"
android:title="Enable RoundR" />
<CheckBoxPreference
android:defaultValue="true"
android:key="start_on_boot"
android:summary="Start RoundR automatically on boot"
android:title="Start on boot" />
<CheckBoxPreference
android:defaultValue="true"
android:key="notification"
android:summary="The notification is required to keep RoundR running in low memory situations"
android:title="Visible Notification" />
</PreferenceCategory>
<PreferenceCategory android:title="RoundR Settings" >
<PreferenceScreen
android:dependency="enable"
android:persistent="false"
android:summary="Enable rounding on specific corners"
android:title="Enabled Corners" >
<CheckBoxPreference
android:defaultValue="true"
android:key="corner0"
android:title="Top Left" />
<CheckBoxPreference
android:defaultValue="true"
android:key="corner1"
android:title="Top Right" />
<CheckBoxPreference
android:defaultValue="true"
android:key="corner2"
android:title="Bottom Left" />
<CheckBoxPreference
android:defaultValue="true"
android:key="corner3"
android:title="Bottom Right" />
</PreferenceScreen>
<mohammad.adib.roundr.SeekBarPreference
android:defaultValue="10"
android:key="radius"
android:max="40"
android:title="Corner Radius"
roundr:min="2"
roundr:unitsLeft=""
roundr:unitsRight="" />
<CheckBoxPreference
android:defaultValue="true"
android:key="overlap1"
android:summary="This also constitutes overlaping of the corners on the notification pull-down"
android:title="Enable on lockscreen" />
<CheckBoxPreference
android:defaultValue="false"
android:key="overlap2"
android:summary="Allows for the corners to overlap the status bar"
android:title="Overlap Status Bar" />
</PreferenceCategory>
</PreferenceScreen>
Can u help me? where is the specific code that i need, i was trying to find it for hours...
Enviado desde mi GT-S5570I usando Tapatalk 2
Click to expand...
Click to collapse
It's this particular code change: https://github.com/MohammadAdib/Roundr/commit/b47ca72867093dbe9b29a99469f48e95a1d369fa
nikwen said:
It's this particular code change: https://github.com/MohammadAdib/Roundr/commit/b47ca72867093dbe9b29a99469f48e95a1d369fa
Click to expand...
Click to collapse
IT WORK'S! IT WORK'S! THANK'S!
But the problem now i how to get clicks from it. Do you know how to do it?
Enviado desde mi GT-S5570I usando Tapatalk 2
DannyGM16 said:
IT WORK'S! IT WORK'S! THANK'S!
But the problem now i how to get clicks from it. Do you know how to do it?
Enviado desde mi GT-S5570I usando Tapatalk 2
Click to expand...
Click to collapse
Great. :good:
What's about adding an onClick listener?
nikwen said:
Great. :good:
What's about adding an onClick listener?
Click to expand...
Click to collapse
I tryed it, but the onClick affects to all the screen...
Enviado desde mi GT-S5570I usando Tapatalk 2

[Q] Change text in another activity on click. how?

Hi there
I am new to this forum as an User, and I am also new to Java and Android, in developing ways. Sorry if there are any language or other mistakes.
So I am trying to make an app for a 'final' school project, which has the follow use:
The user sees an picture, a 'next' (and a 'finish') button. there are 11 pictures (user only sees one)(in the code there are for testing purposes only 3) when the user clicks 'next', the pic no. 2 appears, if he clicks another time next, the pictuer no. 3 appears and so on. (If he clicks finish, he should see a messages which shows him the text: "you've made it until pic xy" but i'm not so far yet.) I tried to do it with this code, but i failed.
Code:
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class VisusActivity extends Activity implements OnClickListener {
ImageView testanzeige;
Button next;
Integer[] bildanzeige = {
R.drawable.visustest,
R.drawable.v2,
R.drawable.v3
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_visus);
testanzeige = (ImageView)findViewById(R.id.testanzeige);
next = (Button)findViewById(R.id.next);
next.setOnClickListener(this);
next.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.visus, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onClick(View v) {
try {
//Toast.makeText(this, getResources().getDisplayMetrics().toString(), Toast.LENGTH_LONG).show();
testanzeige.setImageResource(bildanzeige[0]);
}catch(Exception e){
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
}
};
public void onClick1(View v) {
try {
//Toast.makeText(this, getResources().getDisplayMetrics().toString(), Toast.LENGTH_LONG).show();
testanzeige.setImageResource(bildanzeige[2]);
}catch(Exception e){
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
}
}
}
so what have I to do? no tutorial shows up exactly my problem ( I think it's such a basic thing everyone can do it^^)
thx
rodentooth
Anser
rodentooth said:
Hi there
I am new to this forum as an User, and I am also new to Java and Android, in developing ways. Sorry if there are any language or other mistakes.
So I am trying to make an app for a 'final' school project, which has the follow use:
The user sees an picture, a 'next' (and a 'finish') button. there are 11 pictures (user only sees one)(in the code there are for testing purposes only 3) when the user clicks 'next', the pic no. 2 appears, if he clicks another time next, the pictuer no. 3 appears and so on. (If he clicks finish, he should see a messages which shows him the text: "you've made it until pic xy" but i'm not so far yet.) I tried to do it with this code, but i failed.
Code:
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class VisusActivity extends Activity implements OnClickListener {
ImageView testanzeige;
Button next;
Integer[] bildanzeige = {
R.drawable.visustest,
R.drawable.v2,
R.drawable.v3
};
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_visus);
testanzeige = (ImageView)findViewById(R.id.testanzeige);
next = (Button)findViewById(R.id.next);
next.setOnClickListener(this);
next.setOnClickListener(this);
}
[user=439709]@override[/user]
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.visus, menu);
return true;
}
[user=439709]@override[/user]
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
[user=439709]@override[/user]
public void onClick(View v) {
try {
//Toast.makeText(this, getResources().getDisplayMetrics().toString(), Toast.LENGTH_LONG).show();
testanzeige.setImageResource(bildanzeige[0]);
}catch(Exception e){
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
}
};
public void onClick1(View v) {
try {
//Toast.makeText(this, getResources().getDisplayMetrics().toString(), Toast.LENGTH_LONG).show();
testanzeige.setImageResource(bildanzeige[2]);
}catch(Exception e){
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
}
}
}
so what have I to do? no tutorial shows up exactly my problem ( I think it's such a basic thing everyone can do it^^)
thx
rodentooth
Click to expand...
Click to collapse
I have Make Fresh Java That will help You
Java
Code:
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
/**
* @author AndroidFire
*/
public class JumperPic extends Activity {
Button Nexty;
ImageView Imagey;
int i = 0;
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.jumper);
Nexty = (Button)findViewById(R.id.nextey);
Imagey = (ImageView)findViewById(R.id.imagey);
Nexty.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View arg0) {
i++;
// To Set Your 1 Image Do it Thorough Layout
if (i == 1 ) {
//Your 2 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 2) {
//Your 3 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 3) {
//Your 4 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 4) {
// Your 5 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 5 ) {
//Your 6 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 6) {
//Your 7 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 7 ) {
//Your 8 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 8 ) {
//Your 9 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 9) {
//Your 10 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 10) {
//Image 11 Image
Nexty.setText("Finish");
Toast.makeText(getApplicationContext(), "Your Final Text", Toast.LENGTH_LONG).show();
}
}
});
}
}
Layout
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="@+id/imagey"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/avatar_default_1" />
<Button
android:id="@+id/nextey"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
In Your Java You can use Button.setOnClickLiestner(new View.OnClickLiestner It will bit easier than it because When We Implement Anything in Your Class we need delcare methods @override somethings you can use int to change Image
In My Java I have int values that will change every click on Button according to values it will change imageview you have write java that is tough from Me you can use my one it will bit easier Ok
Thank you new problem
Thank you so very much AndroidFire withoup you i've wouldn't made it this far. So you say I can use your code (with your name in it) in my Project?
AndroidFire said:
you can use my one it will bit easier Ok
Click to expand...
Click to collapse
Now while this problem is solved another problem has come up.
As I told you in my first thread, there is a finish button. It has this use:
when user clicks next 2 times (so if he made it until the 3rd picture) and then clicks finish, he'll Return to the main activity, and instead of the text 'Klicke auf start um zu beginnen' (click on start to begin) the text 'you made it until the 3rd picture' should show up.
If he clicked Next 5 times (6th picture) and clicks finish, he also returns to the main activity, but the text is 'you made it until the 5th picture'.
And so on with the others.
now i dont know, how to implement multiple buttons, how can I learn that? also how did you learn to code, AndroidFire? It's such a masterpiece *-*
I've tried this, but I failed.
the red lines are those, which I made at my own but they unfortunately don't work
Java Main Activity
Code:
package ch.OptiLab.visustest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener {
Button btn1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = (Button) findViewById(R.id.buttonSTART);
btn1.setOnClickListener(this);
[COLOR="red"] Intent intent = getIntent();
if( intent != null)
String inhalt = intent.GetStringExtra("0.1");[/COLOR]
}
@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;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(this,VisusActivity.class));
}
}
XML Main Activity
Code:
<RelativeLayout xmlns:android="(external link)"
xmlns:tools="(external link)"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="ch.OptiLab.visustest.MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="@string/Text1"
android:id="@+id/textView"
android:layout_marginTop="84dp"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:gravity="center_horizontal"
android:singleLine="false" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="@string/Text2"
android:id="@+id/textView2"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="33dp" />
<Button
android:id="@+id/buttonSTART"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="@string/button1"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:layout_marginTop="142dp" />
</RelativeLayout>
Java 2nd activity
Code:
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
/**
* @author AndroidFire
*/
public class VisusActivity extends Activity {
Button next;
ImageView testanzeige;
Button finish;
int i = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_visus);
next = (Button)findViewById(R.id.next);
testanzeige = (ImageView)findViewById(R.id.testanzeige);
[COLOR="red"]finish = (Button)findViewById(R.id.finish);[/COLOR]
next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
i++;
// To Set Your 1 Image Do it Thorough Layout
if (i == 1 ) {
//Your 2 Image
testanzeige.setImageResource(R.drawable.visustest);
[COLOR="Red"]finish.setOnClickListener(new View.OnClickListener() {
Intent i = new Intent(this, MainActivity.class);
String content = "You made it until 2nd picture".toString();
i.putExtra("0.1", content);
}
[/COLOR]
}
else if (i == 2) {
//Your 3 Image
testanzeige.setImageResource(R.drawable.v2);
}
else if (i == 3) {
//Your 4 Image
testanzeige.setImageResource(R.drawable.v3);
}
else if (i == 4) {
// Your 5 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 5 ) {
//Your 6 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 6) {
//Your 7 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 7 ) {
//Your 8 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 8 ) {
//Your 9 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 9) {
//Your 10 Image
testanzeige.setImageResource(R.drawable.visustest);
}
else if (i == 10) {
//Image 11 Image
next.setText("Finish");
Toast.makeText(getApplicationContext(), "Your Final Text", Toast.LENGTH_LONG).show();
}
}
});
}
}
XML 2nd Activity
Code:
<RelativeLayout xmlns:android="(external link)"
(external link)"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="ch.OptiLab.visustest.VisusActivity" >
<ImageView
android:id="@+id/testanzeige"
android:layout_width="231dp"
android:layout_height="231dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="@drawable/v2" />
<Button
android:id="@+id/next"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="16dp"
android:text="@string/NEXTPIC" />
<Button
android:id="@+id/finish"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/next"
android:layout_alignBottom="@+id/next"
android:layout_alignParentLeft="true"
android:text="@string/cantread" />
</RelativeLayout>
The most important strings:
Code:
<string name="Text1">Klicke auf Start um zu beginnen.</string>
<string name="cantread">finish</string>
Thank you so much
other way also not work
Well I have tried another solution, but it didn't work either. What do I have to do?
Code:
Code:
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
/**
* [user=736105]@author[/user] AndroidFire
*/
public class VisusActivity extends Activity {
Button next;
ImageView testanzeige;
Button finish;
int i = 0;
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_visus);
next = (Button)findViewById(R.id.next);
testanzeige = (ImageView)findViewById(R.id.testanzeige);
finish = (Button)findViewById(R.id.finish);
next.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View arg0) {
i++;
// To Set Your 1 Image Do it Thorough Layout
if (i == 1 ) {
//Your 2 Image
testanzeige.setImageResource(R.drawable.visustest);
}
else if (i == 2) {
//Your 3 Image
testanzeige.setImageResource(R.drawable.v2);
}
else if (i == 3) {
//Your 4 Image
testanzeige.setImageResource(R.drawable.v3);
}
else if (i == 4) {
// Your 5 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 5 ) {
//Your 6 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 6) {
//Your 7 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 7 ) {
//Your 8 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 8 ) {
//Your 9 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 9) {
//Your 10 Image
testanzeige.setImageResource(R.drawable.visustest);
}
else if (i == 10) {
//Image 11 Image
next.setText("Finish");
Toast.makeText(getApplicationContext(), "Your Final Text", Toast.LENGTH_LONG).show();
}
}
});
[COLOR="Red"]finish.setOnClickListener(new View.OnClickListener() {
Intent i = new Intent(this, MainActivity.class);
[user=439709]@override[/user]
public void onClick(View arg0) {
i++;
if (i == 1 ) {
String content = "You got 0.1".toString();
i.putExtra("0.1", content);
[/COLOR]
}
}
}
}
I'm assuming you declared your activity in the Manifest?
F'n noob said:
I'm assuming you declared your activity in the Manifest?
Click to expand...
Click to collapse
uhm I think so.
Edit: there are 2 activity-groups in my manifest, so I think they've been declared automatically?
After looking at your code further, you are using onClick methods but aren't implenting an onClickListener. Are your buttons working at all?
yes, they are working fine. I just dont know how to change the text.
rodentooth said:
yes, they are working fine. I just dont know how to change the text.
Click to expand...
Click to collapse
There are two ways I can think of to solve this one.
The first is to create an Application class, declare that in the manifest, and add a variable in there to save how many images have been seen. Just set it in the one activity and in the other read it, and if it's 0, show the start message, and if it's greater than 0 show the message you want.
The cooler way is to use startActivityForResult to go to the picture viewing activity. The picture viewing activity keeps track of how many the user saw and then, when they leave:
Code:
Intent returnData = new Intent();
returnData.putExtra("PICTURES_SEEN", count);
setResult(RESULT_OK, returnData);
Then, in the first activity:
Code:
@Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
int picturesSeen = data.getExtra("PICTURES_SEEN");
// do stuff
}
}
Hopefully that's helpful.
(There's a page in Google's API called "Getting a Result from an Activity" but I can't link to it because I'm a spammernew.)

Categories

Resources