Hey, I was working on progress Bars. But I am having a little trouble. On the following code, The bar seems to work perfectly, but just when its done loading. The app crashes. Please help me out. Thanks in advance
Code:
package com.example.progresses;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ProgressBar;
public class MainActivity extends Activity {
ProgressBar b;
int progressStatus = 0;
static int progress = 0;
Thread t;
Handler hand = new Handler();
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (ProgressBar) findViewById(R.id.progressBar1);
b.setMax(200);
new Thread(new Runnable() {
public void run() {
while (progressStatus <= 200) {
progressStatus = doWork();
hand.post(new Runnable() {
public void run() {
b.setProgress(progressStatus);
}
});
}
b.setVisibility(View.GONE);
}
}).start();
}
private int doWork() {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ++progress;
}
}
LOGCAT
You have to do this via the handler, too:
Code:
b.setVisibility(View.GONE);
Every action regarding the UI from another thread has to be done via an handler.
nikwen said:
You have to do this via the handler, too:
Code:
b.setVisibility(View.GONE);
Every action regarding the UI from another thread has to be done via an handler.
Click to expand...
Click to collapse
Thank you!
hiphop12ism said:
Thanks you!
Click to expand...
Click to collapse
Welcome.
Hi frends im working on my android final year project based on sockets..im using ssynctask to connect socket etc..Everything works fine, since I'm using AsyncTask to create a Socket connection ... the socket works fine in the doInBackground() method, but when I try to send Sensor data from theonSensorChanged() method, I get null pointer exception. I don't know what went wrong. in short Socket returns NULL outside asyncTask Class...can some 1 help me ?..
here is my code
Code:
package com.example.sensorsmart;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements SensorEventListener{
private static final int SERVERPORT = 8222;
private static final String SERVER_IP = "192.168.0.101";
private SensorManager mSensorManager;
private Sensor mAccelerometer;
private TextView tv ;
public ServerSocket serverSocket=null;
public Socket socket = null;
public BufferedReader in ;
public BufferedWriter out;
public PrintWriter pw ;
public FileWriter writer=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new MyTask().execute();
mSensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
mAccelerometer mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mSensorManager.registerListener(this, mAccelerometer,SensorManager.SENSOR_DELAY_NORMAL);
}
public void onStopClick(View view) {
mSensorManager.unregisterListener(this);}
private class MyTask extends AsyncTask<Void, Void, Void>
{
@Override
protected Void doInBackground(Void... arg0) {
try {
serverSocket = new ServerSocket(8222);
} catch (IOException e) {
e.printStackTrace();
}
try {
socket=serverSocket.accept();
Log.i("TcpServer", "CONNECTED");
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
pw = new PrintWriter(socket.getOutputStream(),true);
if(!in.ready())
{
Log.i("TcpServer", "READER IS NOT READY");
}
final String g;
final String c;
String b = null;
Log.i("TcpServer", "GOING");
g=in.readLine();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(),g, Toast.LENGTH_LONG).show();
}
});
} catch (IOException e) {
e.printStackTrace();
String response = e.getCause().toString();
Log.i("TCP",response);
}
return null;
}
}
@Override
public void onSensorChanged(SensorEvent event) {
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
pw.write("g"); //NULL POINT EXCEPTION THROWS HERE
}
}
LOGCAT:
Code:
02-06 11:31:54.250: E/AndroidRuntime(4108): FATAL EXCEPTION: main
02-06 11:31:54.250: E/AndroidRuntime(4108): java.lang.NullPointerException
02-06 11:31:54.250: E/AndroidRuntime(4108): at com.example.sensorsmart.MainActivity.onSensorChanged(MainActivity.java:196)
02-06 11:31:54.250: E/AndroidRuntime(4108): at android.hardware.SystemSensorManager$ListenerDelegate$1.handleMessage(SystemSensorManager.java:204)
02-06 11:31:54.250: E/AndroidRuntime(4108): at android.os.Handler.dispatchMessage(Handler.java:99)
02-06 11:31:54.250: E/AndroidRuntime(4108): at android.os.Looper.loop(Looper.java:137)
02-06 11:31:54.250: E/AndroidRuntime(4108): at android.app.ActivityThread.main(ActivityThread.java:4759)
02-06 11:31:54.250: E/AndroidRuntime(4108): at java.lang.reflect.Method.invokeNative(Native Method)
02-06 11:31:54.250: E/AndroidRuntime(4108): at java.lang.reflect.Method.invoke(Method.java:511)
02-06 11:31:54.250: E/AndroidRuntime(4108): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
02-06 11:31:54.250: E/AndroidRuntime(4108): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:558)
02-06 11:31:54.250: E/AndroidRuntime(4108): at dalvik.system.NativeStart.main(Native Method)
you have to set the variable in onpostexecute() and also use
Code:
new MyTask().execute().get()
so you make sure the async task has finished for sure
Can u gv example ?
warlock9_0 said:
you have to set the variable in onpostexecute() and also use
Code:
new mytask().execute().get()
so you make sure the async task has finished for sure
Click to expand...
Click to collapse
frend can u give me an example ?
forget the execute().get() for now, maybe it is not needed
read the documents for asynctask and change your result type from void, to whatever you want to set
for example if you want only the PrintWriter to be set you can do this
Code:
package com.example.sensorsmart;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements SensorEventListener{
private static final int SERVERPORT = 8222;
private static final String SERVER_IP = "192.168.0.101";
private SensorManager mSensorManager;
private Sensor mAccelerometer;
private TextView tv ;
public ServerSocket serverSocket=null;
public Socket socket = null;
public BufferedReader in ;
public BufferedWriter out;
public PrintWriter pw ;
public FileWriter writer=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new MyTask().execute();
mSensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
mAccelerometer mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mSensorManager.registerListener(this, mAccelerometer,SensorManager.SENSOR_DELAY_NORMAL);
}
public void onStopClick(View view) {
mSensorManager.unregisterListener(this);}
private class MyTask extends AsyncTask<Void, Void, PrintWriter>
{
@Override
protected PrintWriter doInBackground(Void... arg0) {
try {
serverSocket = new ServerSocket(8222);
} catch (IOException e) {
e.printStackTrace();
}
try {
socket=serverSocket.accept();
Log.i("TcpServer", "CONNECTED");
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
pw = new PrintWriter(socket.getOutputStream(),true);
if(!in.ready())
{
Log.i("TcpServer", "READER IS NOT READY");
}
final String g;
final String c;
String b = null;
Log.i("TcpServer", "GOING");
g=in.readLine();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(),g, Toast.LENGTH_LONG).show();
}
});
} catch (IOException e) {
e.printStackTrace();
String response = e.getCause().toString();
Log.i("TCP",response);
}
return pw;
}
protected void onPostExecute(PrintWriter result) {
pw = result;
}
}
@Override
public void onSensorChanged(SensorEvent event) {
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
if(pw!=null) pw.write("g"); //NULL POINT EXCEPTION THROWS HERE
}
}
if you want other variables to be returned too, you can make a custom object as the type of the result
is it possible to pass socket instead mof printwriter?
hi friend thank u for ur reply...is it possible to pass socket in onpostexecute () ?
i tried with below code still socket is null in ONsensor Changed
Code:
private class MyTask extends AsyncTask<Void, Void,Socket>
{
@Override
protected Socket doInBackground(Void... arg0) {
// TODO Auto-generated method stub
try {
serverSocket = new ServerSocket(8222);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
socket=serverSocket.accept();
Log.i("TcpServer", "CONNECTED");
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
pw = new PrintWriter(socket.getOutputStream(),true);
//out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
if(!in.ready())
{
Log.i("TcpServer", "READER IS NOT READY");
}
final String g;
final String c;
String b = null;
Log.i("TcpServer", "GOING");
g=in.readLine();
//Log.i("TcpServer", in.readLine());
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(),g, Toast.LENGTH_LONG).show();
}
});
Log.i("TcpServer", "RECEIVED");
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(),g, Toast.LENGTH_LONG).show();
}
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
String response = e.getCause().toString();
Log.i("TCP",response);
}
return socket;
}
protected void onPostExecute(Socket result) {
socket = result;
}
yes, you can pass the socket like you do
but in the onsensorchanged function you are using the printwriter (pw) you created in the doinbackground function which is null because you haven't passed it to the main thread
so, you either have to make a new object that will pass all the things to the main threat (socket, printwriter, bufferedreader) if you want them all, or pass the printwriter only, or you will initialize them on the post execute function
for example, you can return the socket and then do
Code:
protected void onPostExecute(Socket result) {
socket = result;
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
pw = new PrintWriter(socket.getOutputStream(),true);
}
still null
here is my entire code..i have done exactly what u said...still socket null in OnsensorChanged()
Code:
package com.example.sensorsmart;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements SensorEventListener{
private static final int SERVERPORT = 8222;
private static final String SERVER_IP = "192.168.0.101";
private SensorManager mSensorManager;
private Sensor mAccelerometer;
private TextView tv ;
public ServerSocket serverSocket=null;
public Socket socket = null;
public BufferedReader in ;
public BufferedWriter out;
public PrintWriter pw ;
public FileWriter writer=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new MyTask().execute();
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
public void onStopClick(View view) {
mSensorManager.unregisterListener(this);
}
protected void onResume() {
super.onResume();
}
protected void onStop(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSensorManager.unregisterListener(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.main, menu);
return true;
}
private class MyTask extends AsyncTask<Void, Void,Socket>
{
@Override
protected Socket doInBackground(Void... arg0) {
// TODO Auto-generated method stub
try {
serverSocket = new ServerSocket(8222);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
socket=serverSocket.accept();
Log.i("TcpServer", "CONNECTED");
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
pw = new PrintWriter(socket.getOutputStream(),true);
//out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
if(!in.ready())
{
Log.i("TcpServer", "READER IS NOT READY");
}
final String g;
final String c;
String b = null;
Log.i("TcpServer", "GOING");
g=in.readLine();
//Log.i("TcpServer", in.readLine());
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(),g, Toast.LENGTH_LONG).show();
}
});
Log.i("TcpServer", "RECEIVED");
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(),g, Toast.LENGTH_LONG).show();
}
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
String response = e.getCause().toString();
Log.i("TCP",response);
}
return socket;
}
protected void onPostExecute(Socket result) {
socket = result;
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
pw = new PrintWriter(socket.getOutputStream(),true);
}
}
@Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
@Override
public void onSensorChanged(SensorEvent event) {
pw.println("egaga");
}
public void CloseConn() throws IOException //not used
{
pw.flush();
in.close();
socket.close();
serverSocket.close();
}
}
Code:
public class MainActivity extends Activity implements SensorEventListener{
private static final int SERVERPORT = 8222;
private static final String SERVER_IP = "192.168.0.101";
private SensorManager mSensorManager;
private Sensor mAccelerometer;
private TextView tv ;
public ServerSocket serverSocket=null;
public Socket socket = null;
public BufferedReader in ;
public BufferedWriter out;
public PrintWriter pw ;
public FileWriter writer=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new MyTask().execute();
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
public void onStopClick(View view) {
mSensorManager.unregisterListener(this);
}
protected void onResume() {
super.onResume();
}
protected void onStop(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSensorManager.unregisterListener(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.main, menu);
return true;
}
private class MyTask extends AsyncTask<Void, Void,AllInOne>
{
@Override
protected AllInOne doInBackground(Void... arg0) {
// TODO Auto-generated method stub
try {
serverSocket = new ServerSocket(8222);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
socket=serverSocket.accept();
Log.i("TcpServer", "CONNECTED");
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
pw = new PrintWriter(socket.getOutputStream(),true);
//out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
if(!in.ready())
{
Log.i("TcpServer", "READER IS NOT READY");
}
final String g;
final String c;
String b = null;
Log.i("TcpServer", "GOING");
g=in.readLine();
//Log.i("TcpServer", in.readLine());
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(),g, Toast.LENGTH_LONG).show();
}
});
Log.i("TcpServer", "RECEIVED");
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(),g, Toast.LENGTH_LONG).show();
}
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
String response = e.getCause().toString();
Log.i("TCP",response);
}
return new AllInOne(socket,in,pw);
}
protected void onPostExecute(AllInOne result) {
socket = result.so;
in = result.re;
pw = result.pr;
}
}
@Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
@Override
public void onSensorChanged(SensorEvent event) {
if(pw!=null) pw.println("egaga");
else Log.e("PrintWriter", null);
}
public void CloseConn() throws IOException //not used
{
pw.flush();
in.close();
socket.close();
serverSocket.close();
}
private class AllInOne {
public Socket so;
public BufferedReader re;
public PrintWriter pr;
public AllInOne(Socket s, BufferedReader r, PrintWriter p ){
this.so = s;
this.re = r;
this.pr = p;
}
}
}
try this
since you are initializing in and pw inside the doinbackground, you have to pass them to the main thread
so i added another class to hold all these and i pass them on result
finally you also have to check in the onsensorchanged if the pw is null because the asynctask may have not finished yet when this is called
null
async task not completed because of socket not closed?
Thank u
bro..some how i managed to get it work..thanks a lot for ur time..and nice to meet u..
I am working on an android application that modifies an external MySQL database. I know I can use an intermediate PHP/JSON service to do it, but I rather use JBDC because connection is faster and my project teachers want me to do it this way.
As it's my first app, I started with a simple button and an action(create a database), which actually works (in fact two buttons, the first one doesn't work on skd higher than 9, AsyncTask has to be used in them):
Code:
package com.example.prova;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.sql.*;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button button1 = (Button) findViewById(R.id.btconn1);
final Button button2 = (Button) findViewById(R.id.btconn2);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try
{
String URL = "jdbc:mysql://" + "192.168.1.200" + ":" + "3306";
String USER = "app";
String PASS = "android";
Toast.makeText(getApplicationContext(),
"Conectando a servidor MySQL",
Toast.LENGTH_SHORT).show();
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection(URL, USER, PASS);
Toast.makeText(getApplicationContext(),
"Conectado Servidor MySQL",
Toast.LENGTH_LONG).show();
Statement stmt = conn.createStatement();
String SQL = "CREATE DATABASE SYNC";
stmt.executeUpdate(SQL);
conn.close();
}
catch (ClassNotFoundException e)
{
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_SHORT).show();
}
catch (SQLException e)
{
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_SHORT).show();
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
});
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new LED13ON().execute();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class LED13ON extends AsyncTask<Void, Integer, Void> {
@Override
protected void onPostExecute(Void result){
SystemClock.sleep(2000);
}
@Override
protected void onPreExecute(){
SystemClock.sleep(2100);
}
@Override
protected void onProgressUpdate(Integer... values){
SystemClock.sleep(100);
}
@Override
protected Void doInBackground(Void... arg0){
try
{
String URL = "jdbc:mysql://" + "192.168.1.200" + ":" + "3306";
String USER = "app";
String PASS = "android";
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection(URL, USER, PASS);
Statement stmt = conn.createStatement();
String SQL = "CREATE DATABASE aSYNC";
stmt.executeUpdate(SQL);
conn.close();
}
catch (ClassNotFoundException e)
{
}
catch (SQLException e)
{
}
catch (Exception e)
{
}
return null;
}
}
}
The problem is when I try to use fragments, eclipse returns no errors but JDBC code is not working (logcat gives me no errors too). I know that's only the JDBC code which is not working because it gets inside the LED13ON and makes the SystemClock.sleep(2000), because the button is marked for two seconds. This is the code I have for the fragment in a new class:
Code:
package com.example.smarthome;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Locale;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.NavUtils;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
public class Fragment_main extends Fragment {
public Fragment_main() {
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main,container, false);
Button btn = (Button) rootView.findViewById(R.id.btconn1);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick (View v) {
new LED13ON().execute();
}
});
return rootView;
}
public class LED13ON extends AsyncTask<Void, Integer, Void> {
@Override
protected void onPostExecute(Void result){
SystemClock.sleep(2000);
}
@Override
protected void onPreExecute(){
SystemClock.sleep(2100);
}
@Override
protected void onProgressUpdate(Integer... values){
SystemClock.sleep(100);
}
@Override
protected Void doInBackground(Void... arg0){
try
{
String URL = "jdbc:mysql://" + "192.168.1.200" + ":" + "3306";
String USER = "app";
String PASS = "android";
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection(URL, USER, PASS);
Statement stmt = conn.createStatement();
String SQL = "CREATE DATABASE aSYNC";
stmt.executeUpdate(SQL);
conn.close();
}
catch (ClassNotFoundException e)
{
}
catch (SQLException e)
{
}
catch (Exception e)
{
}
return null;
}
}
}
So I don't understand why being the same code it's not working for the second app, having changed the setOnClickListener to work in the fragment. Can anyone help me? I would really like to use the swipe views for my app as I think it fits more the android Holo style.
Thank you for your time!
EDIT:
I found the solution to my problem:
I logged the exceptions, it gave me the error:
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
Click to expand...
Click to collapse
The solution was to add newInstance in the Class.forName:
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
Click to expand...
Click to collapse
So that's all, now my app is working as I intended. Thanks for everything!
Hi I was looking for tutorials to make a radio app so I followed this one but the problem is that as soon as the app closes the music stops, how do I turn it into a service. Thanks
Code:
import android.app.Activity;
import android.os.Bundle;
import java.io.IOException;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
public class myMain extends Activity implements OnClickListener {
private ProgressBar playSeekBar;
private Button buttonPlay;
private Button buttonStopPlay;
private MediaPlayer player;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initializeUIElements();
initializeMediaPlayer();
}
private void initializeUIElements() {
playSeekBar = (ProgressBar) findViewById(R.id.progressBar1);
playSeekBar.setMax(100);
playSeekBar.setVisibility(View.INVISIBLE);
buttonPlay = (Button) findViewById(R.id.buttonPlay);
buttonPlay.setOnClickListener(this);
buttonStopPlay = (Button) findViewById(R.id.buttonStopPlay);
buttonStopPlay.setEnabled(false);
buttonStopPlay.setOnClickListener(this);
}
public void onClick(View v) {
if (v == buttonPlay) {
startPlaying();
} else if (v == buttonStopPlay) {
stopPlaying();
}
}
private void startPlaying() {
buttonStopPlay.setEnabled(true);
buttonPlay.setEnabled(false);
playSeekBar.setVisibility(View.VISIBLE);
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
}
private void stopPlaying() {
if (player.isPlaying()) {
player.stop();
player.release();
initializeMediaPlayer();
}
buttonPlay.setEnabled(true);
buttonStopPlay.setEnabled(false);
playSeekBar.setVisibility(View.INVISIBLE);
}
private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.setDataSource("stream url");
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
playSeekBar.setSecondaryProgress(percent);
Log.i("Buffering", "" + percent);
}
});
}
@Override
protected void onPause() {
super.onPause();
if (player.isPlaying()) {
player.stop();
}
}
}
benpaterson said:
Hi I was looking for tutorials to make a radio app so I followed this one but the problem is that as soon as the app closes the music stops, how do I turn it into a service. Thanks
Code:
import android.app.Activity;
import android.os.Bundle;
import java.io.IOException;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
public class myMain extends Activity implements OnClickListener {
private ProgressBar playSeekBar;
private Button buttonPlay;
private Button buttonStopPlay;
private MediaPlayer player;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initializeUIElements();
initializeMediaPlayer();
}
private void initializeUIElements() {
playSeekBar = (ProgressBar) findViewById(R.id.progressBar1);
playSeekBar.setMax(100);
playSeekBar.setVisibility(View.INVISIBLE);
buttonPlay = (Button) findViewById(R.id.buttonPlay);
buttonPlay.setOnClickListener(this);
buttonStopPlay = (Button) findViewById(R.id.buttonStopPlay);
buttonStopPlay.setEnabled(false);
buttonStopPlay.setOnClickListener(this);
}
public void onClick(View v) {
if (v == buttonPlay) {
startPlaying();
} else if (v == buttonStopPlay) {
stopPlaying();
}
}
private void startPlaying() {
buttonStopPlay.setEnabled(true);
buttonPlay.setEnabled(false);
playSeekBar.setVisibility(View.VISIBLE);
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
}
private void stopPlaying() {
if (player.isPlaying()) {
player.stop();
player.release();
initializeMediaPlayer();
}
buttonPlay.setEnabled(true);
buttonStopPlay.setEnabled(false);
playSeekBar.setVisibility(View.INVISIBLE);
}
private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.setDataSource("stream url");
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
playSeekBar.setSecondaryProgress(percent);
Log.i("Buffering", "" + percent);
}
});
}
@Override
protected void onPause() {
super.onPause();
if (player.isPlaying()) {
player.stop();
}
}
}
Click to expand...
Click to collapse
You'll have to learn about Android Service and extend that, instead of Activity.
Respected developers , I m creating app of alphabets , I am unable to add sound with imageswitcher,
I want when user press next button , It should give next image with its sound
my code is
Code:
I have sound in Row folder name a,b,c
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ViewSwitcher.ViewFactory;
public class New extends ActionBarActivity implements ViewFactory {
ImageSwitcher is;
int [] imgid = {R.drawable.i1,
R.drawable.i2,
R.drawable.i3,
R.drawable.i4};
Button prev, next;
int count =0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.poetry);
final Button switchact = (Button) findViewById(R.id.btn1);
switchact.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent act2 = new Intent(view.getContext(), MainActivity.class);
startActivity(act2);
}
});
is = (ImageSwitcher)findViewById(R.id.imageSwitcher1);
prev = (Button)findViewById(R.id.button1);
next = (Button)findViewById(R.id.button2);
is.setFactory(this);
is.setInAnimation(this, android.R.anim . slide_in_left);
is.setOutAnimation(this, android.R.anim.slide_out_right);
prev.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(count>0)
{
count--;
try{
is.setImageResource(imgid[count]);
}
catch(Exception e)
{
e.printStackTrace();
}
}
else
{
Toast.makeText(New.this, "First", Toast.LENGTH_LONG).show();
}
}
});
next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(count<imgid.length)
{
try{
is.setImageResource(imgid[count]);
}
catch(Exception e)
{
e.printStackTrace();
}
count++;
}
else
{
Toast.makeText(New.this, "Last", Toast.LENGTH_LONG).show();
}
}
});
}
@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);
}
public boolean appnot(View v){
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = "http://rafeeqsir.in";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "I found a best Urdu Learing App Please try");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
return false;
}
public void about(View v){
{
new AlertDialog.Builder(this)
.setTitle(R.string.app_about)
.setNegativeButton(R.string.str_ok,
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialoginterface, int i)
{
}
})
.show();
}
}
public void exit(View v){
{
new AlertDialog.Builder(this)
.setTitle(R.string.app_exit)
.setIcon(R.drawable.ic_launcher)
.setMessage(R.string.app_exit_message)
.setNegativeButton(R.string.exit,
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialoginterface, int i)
{
System.exit(0);
}
})
.show();
}
}
@Override
public View makeView() {
// TODO Auto-generated method stub
ImageView iv = new ImageView(this);
iv.setScaleType(ImageView.ScaleType.FIT_CENTER);
iv.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
return iv;
}
}
please help me about it