Here is my code
package com.example.akash.myapplication;
//Required import files here
public class MainActivity extends Activity implements Runnable
{
public TextView tex;
public Button button;
public EditText edi;
public static Socket client;
String serverName = "192.168.0.100";
int port = 4444;
protected void onCreate(Bundle savedValues) {
button= (Button) findViewById(R.id.button1);
tex= (TextView) findViewById(R.id.textView1);
edi= (EditText) findViewById(R.id.editText1);
Runnable r = new MainActivity();
final Thread t= new Thread(r);
t.start();
// Register the onClick listener with the implementation above
button.setOnClickListener(new OnClickListener() {
public void onClick(View v){
try {
t.wait();
/*System.out.println("Enter your name: ");
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
System.out.println("Connecting to " + serverName + " on port " + port);*/
client = new Socket(serverName, port);
//System.out.println("Just connected to " + client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
out.writeUTF("Hello from " + client.getLocalSocketAddress());
String msg = edi.getText().toString();
out.writeUTF("Client: " + msg);
t.run();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void run()
{
while(true)
{
try
{
client = new Socket(serverName, port);
if(client.getInputStream()!=null){
InputStream inFromServer = client.getInputStream();
DataInputStream in = new DataInputStream(inFromServer);
tex.append("Server: " + in.readUTF() + "\n");}
client.close();
}catch(Exception e)
{
e.printStackTrace();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
public void test(){
// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
tex.setText("inside test");
/*String locationProvider = LocationManager.GPS_PROVIDER;
Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
t.setText("Latitude: " + lastKnownLocation.getLatitude());*/
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
double d = location.getLatitude();
tex.setText("Latitude: " + d);
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
}
And here is the null pointer error, which I guess is being caused in the run() method. I've been trying to fix this bug since more than couple hours now but all in vain.
01-07 09:05:35.178 28413-28413/com.example.akash.myapplication W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x4187fc08)
01-07 09:05:35.183 28413-28413/com.example.akash.myapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.akash.myapplication, PID: 28413
android.util.SuperNotCalledException: Activity {com.example.akash.myapplication/com.example.akash.myapplication.MainActivity} did not call through to super.onCreate()
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2471)
at android.app.ActivityThread.access$900(ActivityThread.java:175)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5603)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)
I'd really appreciate your help people.
If possible, please share some references or guide me anyway using which I can solve these problems myself and also help others in this great community.
Thankyou in advance.
Updated, the error is smaller now after following #M D
You forget setContentView(R.layout.yourlayout); before initialized views in onCreate(...).
A lot of things in your example are very wrong.
Admittedly, not the reason for the first NPE, but let me be a prophet:
You access tex inside the run method of your runnable MainActivity.
However, tex is initialized in the onCreate method which is part of the android activity life cycle. When you call Runnable r = new MainActivity(); you create a new activity outside that lifecycle so
tex will never be initialized in that new MainActivity
even if it would run into onCreate tex would be a different view, than you'd probably expect and you would create a BufferOverflow or OutOfMemoryError because of infinitely recursive created MainActivities
If you would make your runnable an anonymous implementation inside MainActivity it would probably close over texas you would like it to.
Runnable r = new Runnable {
public void run() {
try {
client = new Socket(serverName, port);
if(client.getInputStream()!=null){
InputStream inFromServer = client.getInputStream();
DataInputStream in = new DataInputStream(inFromServer);
tex.append("Server: " + in.readUTF() + "\n");}
client.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
Related
I want to send value from string (distance to obstacle) to my TextView in main activity.
I tried to use Handler, but still not working (crash) or receive nothing.
A part code which receive data from HC-05 (screen where you see in debug value assignet to variable)
enter image description here
#Override
public void run() {
byte[] buffer = new byte[1024];
int bytes;
while(true){
try {
bytes = inputStream.read(buffer);
final String comingMsg = new String(buffer,0,bytes);
Log.d(TAG,"InputStream: " + comingMsg);
/*mHandler2.post(new Runnable() {
#Override
public void run() {
Message message = new Message();
message.obj = comingMsg;
mHandler2.sendMessage(message);
}
});*/
}catch (IOException e){
Log.e(TAG,"Write: Error reading input." + e.getMessage());
active=false;
break;
}
}
}
Here It's parts of code from MainActivity where I tried put something to get values from service.
[I add, that for this moment i want to see something values from bluetooth in textView. Later I want to create parse string and send custom text to custom TextView - example: FL: (Front Left)- to one textView, FR: (Front Right) - to second textView]
There is method implementThreads(), because I wanted to do 6 Threads to 6 TextView which every time is refreshing value from string in Services (there I tried get value from Bluetooth Service)
Log.d(TAG,"Check intent - result");
if(getIntent().getIntExtra("result",0)==RESULT_OK){
mDevice = getIntent().getExtras().getParcelable("bonded device");
myBluetoothService = new MyBluetoothService(getApplicationContext());
startConnection(mDevice,MY_UUID);
Log.d(TAG,"Check is active service");
checkIfActive();
}
Log.d(TAG,"Check intent - connect_to_paired");
if(getIntent().getIntExtra("connect_to_paired",0)==RESULT_OK){
mDevice = getIntent().getExtras().getParcelable("bonded_paired_device");
myBluetoothService = new MyBluetoothService(getApplicationContext());
startConnection(mDevice,MY_UUID);
Log.d(TAG,"Check is active service");
checkIfActive();
}
}
#Override
public void onStart(){
super.onStart();
myBluetoothService = new MyBluetoothService(getApplicationContext());
}
public void checkIfActive(){
Log.d(TAG,"CheckIfActive: Started");
if(myBluetoothService.active){
Log.d(TAG,"CheckIfActive: Running method implementThreads()");
implementThreads();
}
}
public void implementThreads(){
Log.d(TAG,"ImplementThreads: Started");
Thread thread = new Thread(){
#Override
public void run() {
try{
sleep(100);
}catch (InterruptedException e){
e.printStackTrace();
}
}
};
thread.start();
}
public void startConnection(BluetoothDevice device,UUID uuid){
Log.d(TAG,"StartConnection: Initializing connection");
myBluetoothService.startClient(device,uuid);
}
Thanks all for help, because It's very important for me !
Use this to interect with UI Thread for operations like updating textviews etc.
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
//YOUR CODE HERE
Message message = new Message();
message.obj = comingMsg;
mHandler2.sendMessage(message);
}
});
I am writing a simple server client code to exchange messages, but my app terminates when I try running client.Following is my code for client:
public class Client extends AppCompatActivity {
public void SMessage() throws IOException {
EditText ip = (EditText) findViewById(R.id.ip);
String ipadd, edttxt, output;
PrintStream ps = null;
Intent i;
Scanner sc = null;
ipadd = ip.getText().toString();
Socket s = null;
s = new Socket(ipadd,1234);
i = new Intent(getApplicationContext(), new_activity.class);
startActivity(i);
ScrollView Rl = (ScrollView) findViewById(R.id.scrollView);
sc = new Scanner(s.getInputStream());
EditText et = (EditText) findViewById(R.id.message_txt);
edttxt = et.getText().toString();
ps = new PrintStream(s.getOutputStream());
ps.println(edttxt);
TextView tv1 = new TextView(this);
tv1.setText(edttxt);
tv1.setLayoutParams(new ActionBar.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
tv1.setBackground(getDrawable(R.drawable.ic_action_msg));
}
tv1.setGravity(View.FOCUS_LEFT);
Rl.addView(tv1);
output = sc.nextLine();
if (output.equals("END")) {
s.close();
return;
}
TextView tv2 = new TextView(this);
tv2.setText(output);
tv2.setLayoutParams(new ActionBar.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
tv2.setBackground(getDrawable(R.drawable.ic_action_msg));
}
tv2.setGravity(View.FOCUS_RIGHT);
Rl.addView(tv2);
}
}
Log when app terminates:
E/AndroidRuntime: FATAL EXCEPTION: Thread-4
Process: com.example.devanshi.testapp, PID: 2325
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
at android.support.v7.app.AppCompatDelegateImplBase.<init>(AppCompatDelegateImplBase.java:120)
at android.support.v7.app.AppCompatDelegateImplV9.<init>(AppCompatDelegateImplV9.java:151)
at android.support.v7.app.AppCompatDelegateImplV11.<init>(AppCompatDelegateImplV11.java:31)
at android.support.v7.app.AppCompatDelegateImplV14.<init>(AppCompatDelegateImplV14.java:55)
at android.support.v7.app.AppCompatDelegateImplV23.<init>(AppCompatDelegateImplV23.java:33)
at android.support.v7.app.AppCompatDelegateImplN.<init>(AppCompatDelegateImplN.java:33)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:201)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:185)
at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:519)
at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:190)
at com.example.devanshi.testapp.Client.SMessage(Client.java:27)
at com.example.devanshi.testapp.MainActivity$2.run(MainActivity.java:60)
Main Activity when i call client is as follows:
public void client(View view) {
final Client c = new Client();
Thread t=new Thread(){
public void run(){
try {
c.SMessage();
} catch (IOException e) {
e.printStackTrace();
}
}
};
t.start();
}
I would like to know where did I go wrong and how can I solve it.
Thanks in advance for your response. :)
First, you should set your layout to the activity so you can bind views. Like this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
Second, i am realy confused what are you trying to do in SMessage() method. I think you should do some research about application logic, starting activity and activity lifecycle
I suggest you to use a Service for communication between client and server. It will run in background but you can communicate with server via it. If you start a new activity it will stop your current activity and put it in backstack. Your current activity will not be accessible from the new activity. And you can't run two activity at the same time. So use a service to handle client-server communication and change your client view according to the response received from server via service. It will be a good practice
could anyone help my with my app code. I tryied to make an application that could send data (number or letter) to arduino through bluetooth. This is how my JAVA code look:
package com.example.btprojektas;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
public class MainActivity extends Activity{
private static final String TAG = "btprojektas";
Button btnON, btnOFF;
BluetoothAdapter bluetoothAdapter = null;
BluetoothDevice device = null;
OutputStream outputStream = null;
BluetoothSocket socket = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
btnON = (Button) findViewById(R.id.btnON);
btnOFF = (Button) findViewById(R.id.btnOFF);
if(!bluetoothAdapter.isEnabled()){
Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, 0);
}
loadPairedDevice();
connectBT();
btnON.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
sendData("0");
Toast.makeText(getBaseContext(), "Turn on LED", Toast.LENGTH_SHORT).show();
}
});
btnOFF.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
sendData("1");
Toast.makeText(getBaseContext(), "Turn off LED", Toast.LENGTH_SHORT).show();
}
});
}
private void connectBT() {
if (device != null) {
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); //Standard SerialPortService ID
try {
socket = device.createRfcommSocketToServiceRecord(uuid);
socket.connect();
outputStream = socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void disconnect() {
try {
if (outputStream != null) outputStream.close();
if (socket != null) socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private void loadPairedDevice() {
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
Log.d(TAG, "Device found");
for (BluetoothDevice device : pairedDevices)
if (device.getName().equals("HC-06")) {
this.device = device;
break;
}
}
}
#Override
protected void onPause() {
super.onPause();
disconnect();
}
#Override
protected void onResume() {
super.onResume();
loadPairedDevice();
connectBT();
}
private void sendData(String message) {
byte[] buffer = message.getBytes();
Log.d(TAG,"Send data:"+ message);
try{
outputStream.write (buffer);
} catch (IOException e) {}
}
}
in XML I have two buttons. When the program starts I push one of those buttons and the "Applications ... stopped unexpectedly" appears with fatal exeption fault code:
01-08 15:55:15.439 15354-15354/com.example.btprojektas E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.btprojektas.MainActivity.sendData(MainActivity.java:122)
at com.example.btprojektas.MainActivity.access$000(MainActivity.java:22)
at com.example.btprojektas.MainActivity$1.onClick(MainActivity.java:55)
at android.view.View.performClick(View.java:2485)
at android.view.View$PerformClick.run(View.java:9080)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3687)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
at dalvik.system.NativeStart.main(Native Method)
P.S. Sorry for this question I know that it is quite common but I am new at programming especially JAVA.
It's either the socket or the outputStream. In ConnectBT, you don't check if socket is not null. You directly call socket.connect() assuming socket is valid. The same applies to outputStream. You use it before making sure it's not null.
Also you call
startActivityForResult(enableBluetooth, 0);
but you don't check for the result which is whether bluetooth got enabled or not. This makes your device also suspicious.
Calling
loadPairedDevice();
connectBT();
makes sense only when bluetooth is enabled. Enabling bluetooth can take couple of seconds, but you call them right away.
A couple of tips:
you're calling loadPairedDevice() and connectBT() twice: in onCreate() and in onResume() - do it only once
before using outputStream, check if it's not null (as advised by others)
in sendData(), catch AND print your exception:
try {
if (outputStream != null) {
outputStream.write(buffer);
}
else {
Log.d("TAG", "sendData() - outputStream is null!");
}
}
catch (IOException e) {
e.printStackTrace();
}
in loadPairedDevice(), if you don't find the device "HC-06", your variable device will be null...
enabling bluetooth takes few seconds, so register and listen to ACTION_STATE_CHANGED broadcast Intent. It will contain extra field EXTRA_STATE; look for STATE_ON, and then call your loadPairedDevices() and connectBT() there:
create receiver (inside your MainActivity class):
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
//this is the action you are observing
if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
switch(state) {
//and the state we were looking for
//which means that bluetooth has switched on
//so now you can call your functions
//and set the flag to true, which then use in your
//onClick listeners
case BluetoothAdapter.STATE_ON:
loadPairedDevice();
connectBT();
isBluetoothOn = true;
break;
}
}
}
}
in onCreate(), create IntentFilter and register receiver with it
IntentFilter btFilter = new IntentFilter();
btFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mReceiver, btFilter);
remember to unregister receiver in onPause():
unregisterReceiver(mReceiver);
disable your buttons and enable them in the above listener, when you know BT is switched on; alternatively, keep a flag and use it in your click listeners, eg.:
boolean isBluetoothOn = false;
then later in listener when you get STATE_ON
isBluetooth = true;
And in your button click listener:
//for btnON
public void onClick(View v) {
if (isBluetoothOn) {
sendData("0");
Toast.makeText(getBaseContext(), "Turn on LED", Toast.LENGTH_SHORT).show();
}
}
Do the same for btnOFF.
I have to do a big task while a button click in my android app so i am using runnable to do background work. My works fine without the use of runnable but big task freezes it for a while. After the use of runnable my app is getting crashed on button click.
Here is my code for button onClick function:
public void doSearch(View v)
{
EditText et1 = (EditText) findViewById(R.id.searchText);
String query = et1.getText().toString();
Toast.makeText(this, "Searching Lyrics for "+query, Toast.LENGTH_LONG).show();
final String query1 = query.replaceAll(" ", "+");
Runnable myRunnable = new Runnable() {
#Override
public void run(){
try{
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://example.com/search.php?q="+query1);
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
String line = null;
int count=0,counter=0, disCount=0;
String[] name = new String[20];
String[] link = new String[20];
String[] dis = new String[20];
while ((line = reader.readLine()) != null && counter<20){
if(count == 1){
if(line.contains("href=\"")){
line = line.substring(line.indexOf('=')+2);
link[counter] = line.substring(0, line.indexOf('"'));
line = line.substring(line.indexOf('"')+2);
name[counter] = line.substring(0, line.indexOf('<'));
}
if(disCount==1){
if(line.contains("<b>")){
line = line.replaceAll("<b>", "");
}
if(line.contains("</b>")){
line = line.replaceAll("</b>", "");
}
dis[counter] = line+"...";
counter++;
disCount=0;
}
}
if(line.equals("<div class=\"sen\">")){
count = 1;
}
if(line.equals("<div>")){
disCount=1;
}
if(line.equals("</div>")){
count = 0;
}
}
is.close();
line 82: searchResult(name, link, dis);
}catch(IOException e){} catch(IllegalStateException e){}
}
};
Thread myThread = new Thread(myRunnable);
myThread.start();
}
public void searchResult(String[] name, String[] link, String[] dis)
{
line 91: setContentView(R.layout.results);
nameTemp = name;
linkTemp = link;
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < name.length; i++) {
if(name[i]==null) break;
if(name[0]==null){
Toast.makeText(this, "Sorry! No results matched your query. \n Try again! ", Toast.LENGTH_LONG).show();
}
RowItem item = new RowItem(name[i], dis[i]);
rowItems.add(item);
}
listView = (ListView) findViewById(R.id.result);
CustomListViewAdapter adapter = new CustomListViewAdapter(this, R.layout.list_item, rowItems);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(this, "Loading Lyrics for "+nameTemp[position]+"!", Toast.LENGTH_SHORT).show();
Intent i = new Intent(this, ShowLyricsActivity.class);
i.putExtra("link", linkTemp[position]);
startActivity(i);
}
Here is my logcat:
I/ActivityManager(15444): Starting activity: Intent { act=android.intent.action.MAIN flg=0x10100000 cmp=com.BoxscapeInc.SongLyrics/.MainActivity }
V/ActivityThread(28108): Reporting idle of ActivityRecord{4a2ccbe0 token=android.os.BinderProxy#4a2cc658 {com.BoxscapeInc.SongLyrics/com.BoxscapeInc.SongLyrics.MainActivity}} finished=false
I/WindowManager(15444): Delivering pointer 0 > Window{4a5e2508 com.BoxscapeInc.SongLyrics/com.BoxscapeInc.SongLyrics.MainActivity paused=false}
I/WindowManager(15444): Delivering pointer 1 > Window{4a5e2508 com.BoxscapeInc.SongLyrics/com.BoxscapeInc.SongLyrics.MainActivity paused=false}
I/WindowManager(15444): Dispatching key to Window{4a5e2508 com.BoxscapeInc.SongLyrics/com.BoxscapeInc.SongLyrics.MainActivity paused=false}
I/WindowManager(15444): Dispatching key to Window{4a5e2508 com.BoxscapeInc.SongLyrics/com.BoxscapeInc.SongLyrics.MainActivity paused=false}
I/WindowManager(15444): Delivering pointer 0 > Window{4a5e2508 com.BoxscapeInc.SongLyrics/com.BoxscapeInc.SongLyrics.MainActivity paused=false}
I/WindowManager(15444): Delivering pointer 1 > Window{4a5e2508 com.BoxscapeInc.SongLyrics/com.BoxscapeInc.SongLyrics.MainActivity paused=false}
E/AndroidRuntime(28108): at com.BoxscapeInc.SongLyrics.MainActivity.searchResult(MainActivity.java:92)
E/AndroidRuntime(28108): at com.BoxscapeInc.SongLyrics.MainActivity$100000000.run(MainActivity.java:82)
W/ActivityManager(15444): Force finishing activity com.BoxscapeInc.SongLyrics/.MainActivity
I/ActivityManager(15444): Process com.BoxscapeInc.SongLyrics (pid 28108) has died.
Somebody please help me with this error.
Any help or suggestions would be appreciated.
In Android you can modify UI components only from main thread. You are accessing components in searchResult method called from other thread.
You can do it that way:
et1.post(new Runnable() {
#Override
public void run() {
searchResult(...);
}
});
It will force you to make some variables final, so you can use them in anonymous object. It is OK. See post method.
Personally I would recommend you using AsyncTask class instead of raw Java thread. It composes running one method in background thread and running another method in main thread.
Instead of doing network calls like you have done , I suggest you use this library
you can have a look at here
http://loopj.com/android-async-http/
your code will become very very less , instead of declaring so may asynctask seperately writing bulk of code , you can just use 4 lines of code
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://www.google.com", new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
System.out.println(response);
}
});
It is very efficient in getting the response very quickly in 2 secs.
you don't need to use buffer reader or stuff to format the response. You can directly use the response recieved in string "response" of onSucces method.
I hope this will help you out. :)
The project i am working on needs this type of behavior. The user will be presented with a UI that will give them the option to connect and disconnect to a server. I would also like this UI to show the status of the connection, 'connected or disconnected'. Whenever the user clicks connect, the application will start a thread that handles the connection to the server. The user will still be looking at the main UI. When they start that connection and while the connection remains, i would like the status of the connection to be 'connected'. If the connection is ever broken at any point i would like it to display disconnected. Listed below is what i have so far.
My question is... Am i doing the threading right? So that the phone will not be crushed by the server connection while it is connected?
Also, how do i get the main UI to reflect the connection status of the server and display when the connection is broken?
Thanks in advance! If you have any further questions, please let me know.
The server connection thread.
public class ConnectDevice implements Runnable {
private boolean connected;
private ObjectInputStream ois;
public void run() {
try {
InetAddress host = InetAddress.getByName("192.168.234.1");
Socket socket = new Socket(host.getHostName(), 7777);
connected = true;
while (connected) {
try {
ois = new ObjectInputStream(socket.getInputStream());
String message = (String) ois.readObject();
System.out.println("Message: " + message);
}
catch (Exception e) {
e.printStackTrace();
}
}
ois.close();
} catch (UnknownHostException e) {
e.printStackTrace();
connected = false;
} catch (IOException e) {
e.printStackTrace();
connected = false;
} /*catch (ClassNotFoundException e) {
e.printStackTrace();
connected = false;
}*/
}
}
The main UI and main class.
public class SmartApp extends Activity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.intro);
final Button firstTimeButton = (Button) findViewById(R.id.firstTimeButton);
firstTimeButton.setOnClickListener(
new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
Intent userCreationIntent = new Intent(v.getContext(), UserCreation.class);
startActivityForResult(userCreationIntent, 0);
}
});
final Button connectDeviceButton = (Button) findViewById(R.id.connectDeviceButton);
connectDeviceButton.setOnClickListener(
new View.OnClickListener()
{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Intent connectDeviceIntent = new Intent(v.getContext(), ConnectDevice.class);
//startActivityForResult(connectDeviceIntent, 0);
Thread cThread = new Thread(new ConnectDevice());
cThread.start();
}
});
}
}
Android has a UI thread, which is the only thread that is allowed to update UI elements.
You need to have a background thread doing the work, and posting back to the UI thread when its done.
AsyncTask is an Android class designed to do just that.
Once your worker thread ends its work, and will update the UI element taken by findViewById, it will automatically change on the screen without you having to do anything else.
Check out the AsyncTask, it's tailor made for this sort of thing.