我在send类中创建了其他类的实例,并从send类调用了其他类的函数,但它给出了NPE。我的发送类来自我调用其他类的函数,它是广播类,并且在单击按钮时也会调用此函数。
broadcast broadcastobject.threadfunc(messages);
我创建线程的类是:
public class broadcast {
private DatagramSocket socket;
String str;
private static final int TIMEOUT_MS = 10;
WifiManager mWifi;
EditText et;
DatagramPacket packet;
Button bt;
private static final int SERVERPORT = 11111;
private static final String SERVER_IP = "192.168.1.255";
public void threadfunc(String message){
str=message;
new Thread(new ClientThread()).start();
}
/*
private InetAddress getBroadcastAddress() throws IOException {
DhcpInfo dhcp = mWifi.getDhcpInfo();
if (dhcp == null) {
//Log.d(TAG, "Could not get dhcp info");
return null;
}
int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
byte[] quads = new byte[4];
for (int k = 0; k < 4; k++)
quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);
return InetAddress.getByAddress(quads);
}
*/
class ClientThread implements Runnable {
@Override
public void run() {
try {
socket = new DatagramSocket(SERVERPORT);
socket.setBroadcast(true);
// socket.setSoTimeout(TIMEOUT_MS);
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InetAddress serverAddr = null;
try {
serverAddr = InetAddress.getByName(SERVER_IP);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
packet = new DatagramPacket(str.getBytes(), str.length(),serverAddr,SERVERPORT);
try {
socket.send(packet);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
我的send.java是:
public class Send extends android.app.ListFragment {
WifiManager mwifi;
Button bt1;
boolean testwifi;
TextView tv1;
EditText et1;
String str1;
int id=1;
String messages;
private DataSource datasource;
broadcast broadcastobject;
void wifi() {
mwifi=(WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE);
if(!mwifi.isWifiEnabled())
{
if(mwifi.getWifiState()!=WifiManager.WIFI_STATE_ENABLED)
mwifi.setWifiEnabled(true);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.send, container, false);
datasource = new DataSource(getActivity());
datasource.open();
List<Message> values = datasource.getAllMessages();
// Use the SimpleCursorAdapter to show the
// elements in a ListView
ArrayAdapter<Message> adapter = new ArrayAdapter<Message>(getActivity(), android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
bt1=(Button)rootView.findViewById(R.id.button1);
tv1=(TextView)rootView.findViewById(R.id.textView1);
et1=(EditText)rootView.findViewById(R.id.editText1);
bt1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
@SuppressWarnings("unchecked")
ArrayAdapter<Message> adapter = (ArrayAdapter<Message>) getListAdapter();
Message message = null;
/* ConnectivityManager cn= (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cn.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
testwifi=networkInfo.isConnected();
if(!testwifi)
tv1.setText("wifi is off");
else
tv1.setText("wifi is on");*/
wifi();
// Save the Data in Database
messages=et1.getText().toString();
// check if any of the fields are vaccant
if(messages.equals(""))
{
Toast.makeText(getActivity().getApplicationContext(), "Field Vaccant", Toast.LENGTH_LONG).show();
return;
}
else
{
message = datasource.createMessage(messages);
adapter.add(message);
// broadcastobject=new broadcast(messages);
//broadcastobject.start();
broadcastobject.threadfunc(messages);
et1.setText("");
}
adapter.notifyDataSetChanged();
}
});
return rootView;
}
/*public class MyLocationListener implements LocationListener
{
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
String Text = "My location is: " +
"Latitude = " + loc.getLatitude() +
"Longitude = " + loc.getLongitude();
//finish();
Toast.makeText( getActivity().getApplicationContext(),Text,Toast.LENGTH_SHORT).show();
}
public void onProviderDisabled(String provider)
{
Toast.makeText(getActivity(). getApplicationContext(),"GPS Disabled",Toast.LENGTH_SHORT ).show();
}
public void onProviderEnabled(String provider)
{
Toast.makeText( getActivity().getApplicationContext(),"GPS Enabled",Toast.LENGTH_SHORT).show();
}
@Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}*/
@Override
public void onResume() {
datasource.open();
super.onResume();
}
@Override
public void onPause() {
datasource.close();
super.onPause();
}
}
我的日志猫是:
09-01 17:35:50.350: D/gralloc_goldfish(3557): Emulator without GPU emulation detected.
09-01 17:36:10.300: D/AndroidRuntime(3557): Shutting down VM
09-01 17:36:10.309: W/dalvikvm(3557): threadid=1: thread exiting with uncaught exception (group=0x409961f8)
09-01 17:36:10.369: E/AndroidRuntime(3557): FATAL EXCEPTION: main
09-01 17:36:10.369: E/AndroidRuntime(3557): java.lang.NullPointerException
09-01 17:36:10.369: E/AndroidRuntime(3557): at soft.b.peopleassist.Send$1.onClick(Send.java:114)
09-01 17:36:10.369: E/AndroidRuntime(3557): at android.view.View.performClick(View.java:3480)
09-01 17:36:10.369: E/AndroidRuntime(3557): at android.view.View$PerformClick.run(View.java:13983)
09-01 17:36:10.369: E/AndroidRuntime(3557): at android.os.Handler.handleCallback(Handler.java:605)
09-01 17:36:10.369: E/AndroidRuntime(3557): at android.os.Handler.dispatchMessage(Handler.java:92)
09-01 17:36:10.369: E/AndroidRuntime(3557): at android.os.Looper.loop(Looper.java:137)
09-01 17:36:10.369: E/AndroidRuntime(3557): at android.app.ActivityThread.main(ActivityThread.java:4340)
09-01 17:36:10.369: E/AndroidRuntime(3557): at java.lang.reflect.Method.invokeNative(Native Method)
09-01 17:36:10.369: E/AndroidRuntime(3557): at java.lang.reflect.Method.invoke(Method.java:511)
09-01 17:36:10.369: E/AndroidRuntime(3557): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
09-01 17:36:10.369: E/AndroidRuntime(3557): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
09-01 17:36:10.369: E/AndroidRuntime(3557): at dalvik.system.NativeStart.main(Native Method)
09-01 17:36:13.150: I/Process(3557): Sending signal. PID: 3557 SIG: 9
答案 0 :(得分:1)
您正在接收null
指针,因为您尚未创建任何类broadcast
的对象,并且正在尝试调用该类中存在的函数。由于该函数不是静态的,因此如果不使用该类的对象,则无法使用它。因此,首先需要在调用函数之前创建一个对象,如:
broadcast broadcastobject = new broadcast();