app was stoped working error message

  • Thread starter Thread starter AC Question
  • Start date Start date
A

AC Question

hello i have an application that connect to specifif device called "Aboabdo" when i open this application it connect to this device then stop the app with message "app was stoped" can i know reason the code is

Code:
package.com.example.ramadan.proj0;
import android.database.Cursor;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.telephony.SmsManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

import android.widget.ArrayAdapter;
import android.widget.AdapterView;

public class MainActivity extends AppCompatActivity {
    private Set<BluetoothDevice> pairedDevices;
    private BluetoothAdapter myBluetooth = null;
    private String DEVICE_ADDRESS="Aboabdo";
    private BluetoothDevice device;
    boolean found=false;
    BluetoothSocket btSocket = null;
    OutputStream out;
    InputStream input;
    ListView devicelist;
    private static final int DISCOVERABLE_DURATION=500;
    private static final int ENABLE_BT_REQUEST_CODE=1;
    DatabaseHelper help;
    ArrayList<list> items;
    //SPP UUID. Look for it
    static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ArrayList<list> items=new ArrayList<list>();

        help=new DatabaseHelper(this);

        addData();

        myBluetooth = BluetoothAdapter.getDefaultAdapter();
        if (myBluetooth == null) {
            // Device does not support Bluetooth
            Toast.makeText(getApplicationContext(),"Device doesnt Support Bluetooth",Toast.LENGTH_SHORT).show();
      finish();
        }else{
        if(!myBluetooth.isEnabled())

        {

            Intent enableAdapter = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

            startActivityForResult(enableAdapter, 0);

        }}

        //////////////////////////////////////////////

        device();

        if(found){
            try {
                btSocket = device.createRfcommSocketToServiceRecord(myUUID); btSocket.connect();

            }catch (IOException ex){
                Toast.makeText(getApplicationContext(),ex.getMessage(),Toast.LENGTH_LONG).show();
            }
            try {
               out=btSocket.getOutputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
               input=btSocket.getInputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        else{

            Toast.makeText(getApplicationContext(),"Please make sure of your device",Toast.LENGTH_LONG).show();finish();
        }
        /////////////////////////////////////////////////////////////////////////////////////////////////////
        final Handler handler = new Handler();
        Timer timer = new Timer();
        TimerTask doAsynchronousTask = new TimerTask() {
            @Override
            public void run() {
                handler.post(new Runnable() {
                    public void run() {
                        try {
                            //yout method here
                            fill();
                        } catch (Exception e) {
                        }
                    }
                });
            }
        };
        timer.schedule(doAsynchronousTask, 0, 900000); //execute in every 15 ms
       //fill();
        mylist list=new mylist(items);

        devicelist = (ListView)findViewById(R.id.listView);
        devicelist.setAdapter(list);
      devicelist.setOnClickListener((View.OnClickListener) myListClickListener);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();

        try {
            btSocket.close();
        } catch (IOException e) {
        }
    }
    ///////////////////////////
    public void onActivityResult(int requestCode, int resultCode,Intent data) {

        if (requestCode == ENABLE_BT_REQUEST_CODE) {
            // other code
        } else if (requestCode == 0){

            if (resultCode == DISCOVERABLE_DURATION){
                Toast.makeText(getApplicationContext(), "Your device is now discoverable by other devices for " +
                                DISCOVERABLE_DURATION + " seconds",
                        Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getApplicationContext(), "Fail to enable discoverability on your device.",
                        Toast.LENGTH_SHORT).show();
            }
        }}

    private AdapterView.OnItemClickListener myListClickListener = new AdapterView.OnItemClickListener()
    {
        public void onItemClick (AdapterView<?> av, View v, int arg2, long arg3)
        {
            // Get the device MAC address, the last 17 chars in the View
            TextView  txtname=(TextView)v.findViewById(R.id.textView3);

            Cursor c=help.retrievecolumn(txtname.getText().toString());
            String n="";
            float re=0;
            if(c.getCount()>0){

                while (c.moveToNext()) {
                    n= c.getString(0);
                    re=c.getFloat(2);
                }}
                   // String address ;

            // Make an intent to start next activity.
            Intent i = new Intent(MainActivity.this, Show.class);

            //Change the activity.
            i.putExtra("name", n);
            i.putExtra("itemename", txtname.getText().toString());
            i.putExtra("scale", re);
            startActivity(i);
        }
    };
    /////////////////////////////////////////////
    public void fill(){

        Cursor c=help.retrieveData();
        if(c.getCount()>0){
            list l=new list();
            while (c.moveToNext()){
                l.name=c.getString(1);
                // Log.d(null,l.name);

                //out.write(c.getString(0).toString().getBytes());
                try {
                    out.write(c.getString(0).toString().getBytes());
                } catch (IOException e) {
                    e.printStackTrace();
                }
                byte[] b=new byte[24];
                float re=0;
                try {
                    re=input.read(b);
                    if(re<=c.getFloat(2)){
                        //send sms to user
                        Cursor s=help.retrieveuser();
                        if(s.getCount()>0) {
                            SmsManager msg = SmsManager.getDefault();
                            String message = "please buy alot of "+c.getString(1);
                            msg.sendTextMessage( c.getString(1).toString(),null,message,null,null);
                            /*Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("sms:" + phoneNumber));
                                    intent.putExtra("sms_body", message);
                                    startActivity(intent);*/
                        }
                        ////////////////////////////////
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }

                l.scale=re;
                items.add(l);
            }
        }else{return;}
    }
    public float  read(String x){
        //Calendar c=Calendar.getInstance();
        try {
            out.write(x.toString().getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] b=new byte[24];
        float re=0;
        try {
            re=input.read(b);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return re;
    }
    public void device(){
        pairedDevices = myBluetooth.getBondedDevices();
        if(pairedDevices.isEmpty()) {

            Toast.makeText(getApplicationContext(),"Please Pair the Device first",Toast.LENGTH_SHORT).show();

        } else {

            for (BluetoothDevice iterator : pairedDevices) {

                if(iterator.getName().equals(DEVICE_ADDRESS)) //Replace with iterator.getName() if comparing Device names.

                {

                    device=iterator; //device is an object of type BluetoothDevice

                    found=true;
                    myBluetooth.getDefaultAdapter().cancelDiscovery();

                    break;

                } } }
    }//end of function device();

    private void Disconnect()
    {
        if (btSocket!=null) //If the btSocket is busy
        {
            try
            {
                btSocket.close(); //close connection
            }
            catch (IOException ex)
            { Toast.makeText(getApplicationContext(),ex.getMessage(),Toast.LENGTH_LONG).show();}
        }
        finish(); //return to the first layout

    }
   public void addData(){

       help.insertData("1","Tomate",3.0);
       help.insertData("2","Carrot",2.0);
       help.insertData("3","Apple",1.0);
       help.insertData("4","Banana",2.0);
       help.insertuser("sayed","01120325303");
   }

    ///////////////////////////////////
    private void readFromSensor(String c)
    {
        if (btSocket!=null)
        {
            try
            {
               out.write(c.toString().getBytes());
            }
            catch (IOException e)
            {
                Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_LONG).show();}
            }
        }

    ///class for list
    class mylist extends BaseAdapter
    {
        ArrayList<list> items=new ArrayList<list>();

        mylist( ArrayList<list> items){
            this.items=items;
        }

        @Override
    public int getCount(){
   return items.size();
    }
        @Override
        public String getItem(int position){
            return  items.get(position).name;
        }
        @Override
        public long getItemId(int position){
           return position;
        }
        @Override
        public View getView(int i, View view, ViewGroup viewroup){
            LayoutInflater inflate=getLayoutInflater();
            View view1=inflate.inflate(R.layout.row,null);
            TextView txtname=(TextView) view1.findViewById(R.id.textView3);
            TextView txtscale=(TextView) view1.findViewById(R.id.textView2);
            txtname.setText(items.get(i).name);
            txtscale.setText(items.get(i).scale.toString());
            return view1;
        }
    }
/*private 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(MESSAGE_READ, bytes, -1, buffer)
                        .sendToTarget();
            } catch (IOException e) {
                break;
            }
        }
    }

    public void write(byte[] bytes) {
        try {
            mmOutStream.write(bytes);
        } catch (IOException e) { }
    }

    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
    }
}*/
}
 
Last edited by a moderator:

Members online

Forum statistics

Threads
956,428
Messages
6,968,222
Members
3,163,542
Latest member
04ijordan