Hi I am creating a client-server application with an android device as the client. In my application, my client (android device) sends a request and the server has a response to the request.
I noticed that any method that causes the main thread to wait has to be done on a different thread. I am trying to do that but in my case use a ThreadExecutor. I implemented a helper Runnable class with I pass my ObjectInputStream to but for some reason, its always null. I have checked on a number of questions here but it seems most of them are about how to pass from one activity to another. However I would like to pass from my activity to my helper class and I am not sure of what to do.
Here is my code, I hope it makes more sense.
package com.dozie.service;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StringWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import com.dcloud.common.Event;
import com.dcloud.common.Message;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class RegisterActivity extends Activity {
private Button registerButton;
private Button cancelButton;
private TextView errorText;
private EditText firstnameField, lastnameField, passwordField, cPasswordField, usernameField;
private String fname, lname, pword, cPword, uname;
private Socket socket;
private TextWatcher fnameWatcher, lnameWatcher, pwordWatcher, cPwordWatcher, unameWatcher;
protected ObjectOutputStream os;
protected ObjectInputStream is;
private ExecutorService threadPool;
private RegisterWorker worker;
public static final String PASSWORD_PATTERN = "((?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{6,20})";
public static final String USERNAME_PATTERN = "^[A-z0-9_-]{5,20}$";
public static final String TAG = RegisterActivity.class.getName();
public static final int SAMEFIRSTUSER = 100; //same first name and username,
public static final int SAMELASTUSER = 200; //same last name and username
public static final int SAMEPASSFIRST = 300; //same password and firstname
public static final int SAMEPASSLAST = 400; //same password and lastname
public static final int SAMEPASSUSER = 500; //same password and username
public static final int USERNOTMATCH = 600; //username does not match
public static final int PASSNOTMATCH = 700; //password does not match
public static final int CPASS_DIFF = 800; //password and confirm password are different
public static final int GOODINPUT = 1; //every input is good
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
registerButton = (Button) findViewById(R.id.register_id);
cancelButton = (Button) findViewById(R.id.cancel_id);
firstnameField = (EditText) findViewById(R.id.firstname_id);
lastnameField = (EditText) findViewById(R.id.lastname_id);
passwordField = (EditText) findViewById(R.id.rpassword_id);
cPasswordField = (EditText) findViewById(R.id.rcpassword_id);
usernameField = (EditText) findViewById(R.id.rusername_id);
errorText = (TextView) findViewById(R.id.errorText_id);
fname="";lname="";pword="";cPword="";uname="";
//initialize TextWatchers
initializeWatchers();
// add TextWatchers
firstnameField.addTextChangedListener(fnameWatcher);
lastnameField.addTextChangedListener(lnameWatcher);
passwordField.addTextChangedListener(pwordWatcher);
cPasswordField.addTextChangedListener(cPwordWatcher);
usernameField.addTextChangedListener(unameWatcher);
cancelButton.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
firstnameField.setText("");
lastnameField.setText("");
passwordField.setText("");
cPasswordField.setText("");
usernameField.setText("");
setResult(RESULT_CANCELED);
finish();
}
});
}
#Override
public void onStart()
{
super.onStart();
Log.d(TAG, "onStart()");
Intent intent = getIntent();
final String address = intent.getStringExtra("ipAddress");
final int port = intent.getIntExtra("port", 6060);
threadPool = Executors.newFixedThreadPool(2);
new Thread(new Runnable()
{
#Override
public void run() {
// TODO Auto-generated method stub
try {
Log.i(TAG, "Trying to Connect to "+ address + " on " + port);
socket = new Socket(address, port);
Log.i(TAG, "Connection established!");
os = new ObjectOutputStream(new DataOutputStream(socket.getOutputStream()));
is = new ObjectInputStream(new DataInputStream(socket.getInputStream()));
Log.i(TAG, "Client connected to server.");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
Log.e(TAG, "UnknownHostException", e);
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e(TAG, "I/O Exception", e);
}
}
}).start();
// threadPool.execute(worker = new RegisterWorker(is));;
}
#Override
public void onPause()
{
super.onPause();
Log.d(TAG, "onPause()");
threadPool.shutdown();
Message out = new Message("disconnect");
out.setRequest(Event.Request.DISCONNECT);
try {
os.writeObject(out);
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e(TAG, "I/O Exception", e);
}
finally
{
try {
is.close();
os.close();
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Log.i(TAG, "socket closed");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_register, menu);
return true;
}
public int validateInput(String [] input)
{
String firstname = input[0];
String lastname = input[1];
String password = input[2];
String cpassword = input[3];
String username = input[4];
Pattern pattern = Pattern.compile(PASSWORD_PATTERN);
Matcher matcher = pattern.matcher(password);
Pattern p = Pattern.compile(USERNAME_PATTERN);
Matcher m = p.matcher(username);
if(firstname.equals(username))
return RegisterActivity.SAMEFIRSTUSER;
if(lastname.equals(username))
return RegisterActivity.SAMELASTUSER;
if(firstname.equals(password))
return RegisterActivity.SAMEPASSFIRST;
if(lastname.equals(password))
return RegisterActivity.SAMEPASSLAST;
if(password.equals(username))
return RegisterActivity.SAMEPASSUSER;
if(!password.equals(cpassword))
return RegisterActivity.CPASS_DIFF;
if(!matcher.matches())
return RegisterActivity.PASSNOTMATCH;
if(!m.matches())
return RegisterActivity.USERNOTMATCH;
return RegisterActivity.GOODINPUT;
}
public void registerUser(View v)
{
String [] input = getUserInformation();
int result = validateInput(input);
switch(result)
{
case RegisterActivity.GOODINPUT:
Intent info = new Intent();
info.putExtra("username", input[4]);
registerUser(input);
if(worker.getServerResponse() != null)
{
if(worker.getServerResponse().getResponse() == Event.Response.REQUEST_SUCCESSFUL)
{
threadPool.shutdown();
setResult(RESULT_OK, info);
finish();
Log.i(TAG, "registerUser(): data input successful!");
}
else if(worker.getServerResponse().getResponse() == Event.Response.REQUEST_UNSUCCESSFUL)
{
threadPool.execute(worker);
Log.i(TAG, "registerUser(): data input unsuccessful!");
}
}
break;
case RegisterActivity.SAMEFIRSTUSER:
errorText.setText("username should not be the same as firstname");
Log.i(TAG, "registerUser(): username same as firstname");break;
case RegisterActivity.SAMELASTUSER:
errorText.setText("username should not be the same as lastname");
Log.i(TAG, "registerUser(): username same as lastname");break;
case RegisterActivity.SAMEPASSFIRST:
errorText.setText("password should not be the same as firstname");
Log.i(TAG, "registerUser(): password same as firstname");break;
case RegisterActivity.SAMEPASSLAST:
errorText.setText("password should not be the same as lastname");
Log.i(TAG, "registerUser(): password same as lastname");break;
case RegisterActivity.SAMEPASSUSER:
errorText.setText("password should not be the same as username");
Log.i(TAG, "registerUser(): password same as username");break;
case RegisterActivity.CPASS_DIFF:
errorText.setText("password and confirm password are not the same");
Log.i(TAG, "registerUser(): password and confirm password not the same");break;
case RegisterActivity.PASSNOTMATCH:
errorText.setText("password format wrong. Password should contain 6-20 characters\n" +
"characters containing at least 1 digit, 1 lower case alphabet and 1 upper case character");
Log.i(TAG, "registerUser(): password format not correct");break;
case RegisterActivity.USERNOTMATCH:
errorText.setText("username format wrong. username should contain 5-20 characters " +
"and should have to special characters");
Log.i(TAG, "registerUser(): username format not correct");break;
default:
Log.i(TAG, "registerUser(): Code not handled");break;
}
}
public String [] getUserInformation()
{
String firstname = firstnameField.getText().toString();
String lastname = lastnameField.getText().toString();
String password = passwordField.getText().toString();
String cpassword = cPasswordField.getText().toString();
String username = usernameField.getText().toString();
String [] input = {firstname, lastname, password, cpassword, username};
return input;
}
public void initializeWatchers()
{
fnameWatcher = new TextWatcher()
{
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
fname = firstnameField.getText().toString();
fname.trim();
updateButton();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
};
lnameWatcher = new TextWatcher()
{
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
lname = lastnameField.getText().toString();
lname.trim();
updateButton();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
};
pwordWatcher = new TextWatcher()
{
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
pword = passwordField.getText().toString();
pword.trim();
updateButton();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
};
cPwordWatcher = new TextWatcher()
{
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
cPword = cPasswordField.getText().toString();
cPword.trim();
updateButton();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
};
unameWatcher = new TextWatcher()
{
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
uname = usernameField.getText().toString();
uname.trim();
updateButton();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
};
}
public void updateButton()
{
boolean enabled = fname.length()>0 && lname.length()>0 && pword.length()>0
&& cPword.length()>0 && uname.length() >0;
registerButton.setEnabled(enabled);
}
public void registerUser(String [] input)
{
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("Register");
doc.appendChild(rootElement);
Element user = doc.createElement("user");
rootElement.appendChild(user);
Element firstname = doc.createElement("firstname");
firstname.appendChild(doc.createTextNode(input[0]));
user.appendChild(firstname);
Element lastname = doc.createElement("lastname");
lastname.appendChild(doc.createTextNode(input[1]));
user.appendChild(lastname);
Element password = doc.createElement("password");
password.appendChild(doc.createTextNode(input[2]));
user.appendChild(password);
Element username = doc.createElement("username");
username.appendChild(doc.createTextNode(input[4]));
user.appendChild(username);
StringWriter writer = new StringWriter();
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.transform(new DOMSource(doc), new StreamResult(writer));
String content = writer.toString();
Message out = new Message(content);
out.setRequest(Event.Request.REGISTER);
os.writeObject(out);
Log.d(TAG, "registerUser(): Register message sent");
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
Log.e(TAG, "onActivityReturn(): ParserConfigurationException error", e);
} catch (TransformerException e) {
// TODO Auto-generated catch block
Log.e(TAG, "onActivityReturn(): TransformerException error", e);
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e(TAG, "onActivityReturn(): IOException error", e);
}
}
}
<p>And for my runnable class</p>
package com.dozie.service;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.OptionalDataException;
import android.util.Log;
import com.dcloud.common.Event;
import com.dcloud.common.Message;
public class RegisterWorker implements Runnable{
private ObjectInputStream is;
private Message in;
public static final String TAG = RegisterWorker.class.getName();
public RegisterWorker(ObjectInputStream is)
{
this.is = is;
if(this.is == null)
System.out.println("null");
}
#Override
public void run() {
// TODO Auto-generated method stub
try {
while((in = (Message) is.readObject())!=null)
{
if(in.getResponse() == Event.Response.REQUEST_SUCCESSFUL)
{
Log.d(TAG, "Login Response: "+in.getMessage());
}
else if(in.getResponse() == Event.Response.REQUEST_UNSUCCESSFUL)
{
Log.d(TAG, "Login Response: "+in.getMessage());
//give reason for rejection
}
}
} catch (OptionalDataException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Message getServerResponse()
{
return in;
}
}
I think the code you're writing is way more complicated than it needs to be. If you want to pass variables to a Thread, which is what I think you're trying to do, just do this:
public Worker extends AsyncTask<Arguments, Void, Void> {
// method names may be slightly incorrect, writing this from memory
public void runInBackground(Arguments...args) {
// do what you want to do in the background
}
}
Then start your thread:
Arguments args = new Arguments(arg1, arg2); // whatever you want to pass along
new Worker().execute(args);
Where Arguments can be any class, using this as an example.
Hope this helps.
Simple way is create a static variable and assign the value to it.
Other Solution is create an object with list of values to be carried between the runnable and activity, and pass this object when creating instance
in your case it may look like
MyObject myObject = null;
public RegisterWorker(ObjectInputStream is, MyObject myObject)
{
this.is = is;
this.myObject=myObject;
if(this.is == null)
System.out.println("null");
}
and when processing is finished you add a method where by you can return the object
so your activity class can call that method and use it for further processing.
public MyObject getMyObject(){
retunr myObject
}
But one more way you can try is, Use AsyncTask. Where by you can mention what to return while creating AsyncTask.
Related
Im almost getting to the end of my Sound bar project (2 arduinos, relays, digital potentiometers, leds, i2c, bluetooth and ir remote, diy amplifier,...) and I`m stuck.
This is my first time using android studio and things are becoming so hard for me.
I created an app with a few buttons, switch, sliders and dropdown menu that connects to bluetooth module and sends values to my arduino.
Now I need to add a script that would receive values that arduino is sending (got arduino code done), and would eventualy set buttons clickable/unclickable and set slider positions depending on values being received thru bluetooth.
Can somebody please show me the way to read values from bluetooth and store them in integer or something so that buttons could be disabled and enabled with if(integer=x); statements.
I will post my java code (App is almost done, excepet for sliders and this bluetooth receive part) and I will post the code I came with so far...
I`m going nuts on this one.
Thank you for help :)
package com.interface80.soundbarcontrol;
import androidx.appcompat.app.AppCompatActivity;
import android.content.pm.ActivityInfo;
import android.icu.text.Transliterator;
import android.os.Build;
import android.os.*;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.AsyncTask;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.util.Set;
import java.util.UUID;
public class Remote extends Activity implements AdapterView.OnItemSelectedListener {
private static final String TAG = "BlueTest5-Controlling";
private int mMaxChars = 50000;//Default//change this to string..........
private UUID mDeviceUUID;
private BluetoothSocket mBTSocket;
private ReadInput mReadThread = null;
private boolean mIsUserInitiatedDisconnect = false;
private boolean mIsBluetoothConnected = false;
private int mLastSpinnerPosition = 0;
private Button mBtnDisconnect;
private BluetoothDevice mDevice;
final static String on="92";//on
final static String off="79";//off
final static String subon="10";//subon
final static String suboff="15";//suboff
final static String zero="20";//zeroDB
final static String six="25";//sixDB
final static String twelwe="30";//twelweDB
final static String userBoost="40";
final static String softBoost="45";
final static String normalBoost="50";
final static String hardBoost="55";
final static String overloadOn="60";
final static String overloadOff="65";
Switch toggle; //outside oncreate
private ProgressDialog progressDialog;
Button btnon,btnoff, btnsubon, btnsuboff, btnzero, btnsix, btntwelwe;
Switch overloadSwitch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_remote);
Spinner spinnerPresets = (Spinner) findViewById(R.id.spinnerPresets);
ArrayAdapter<String> adapterPresets = new ArrayAdapter<String>(Remote.this,
android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.arrayPresets));
adapterPresets.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerPresets.setAdapter(adapterPresets);
spinnerPresets.setOnItemSelectedListener(this);
ActivityHelper.initialize(this);
// mBtnDisconnect = (Button) findViewById(R.id.btnDisconnect);
btnon = (Button) findViewById(R.id.on);
btnoff = (Button) findViewById(R.id.off);
btnsubon = (Button) findViewById(R.id.subon);
btnsuboff = (Button) findViewById(R.id.suboff);
btnzero = (Button) findViewById(R.id.zero);
btnsix = (Button) findViewById(R.id.six);
btntwelwe = (Button) findViewById(R.id.twelwe);
overloadSwitch = (Switch) findViewById(R.id.overloadSwitch);
Intent intent = getIntent();
Bundle b = intent.getExtras();
mDevice = b.getParcelable(MainActivity.DEVICE_EXTRA);
mDeviceUUID = UUID.fromString(b.getString(MainActivity.DEVICE_UUID));
mMaxChars = b.getInt(MainActivity.BUFFER_SIZE);
Log.d(TAG, "Ready");
btnon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
mBTSocket.getOutputStream().write(on.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
btnoff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
mBTSocket.getOutputStream().write(off.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
btnsubon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
mBTSocket.getOutputStream().write(subon.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
btnsuboff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
mBTSocket.getOutputStream().write(suboff.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
btnzero.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
mBTSocket.getOutputStream().write(zero.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
btnsix.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
mBTSocket.getOutputStream().write(six.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
btntwelwe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
mBTSocket.getOutputStream().write(twelwe.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String text = parent.getItemAtPosition(position).toString();
if (mLastSpinnerPosition == position)
{
return;
}
mLastSpinnerPosition = position;
if (0 == position) {
Toast.makeText(parent.getContext(), "Boost controlled by user.", Toast.LENGTH_SHORT).show();
btnzero.setEnabled(true);
btnsix.setEnabled(true);
btntwelwe.setEnabled(true);
try {
mBTSocket.getOutputStream().write(userBoost.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return; //do nothing
}
if (1 == position) {
try {
mBTSocket.getOutputStream().write(softBoost.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(parent.getContext(), "DynaBoost control.", Toast.LENGTH_SHORT).show();
btnzero.setEnabled(false);
btnsix.setEnabled(false);
btntwelwe.setEnabled(false);
return; //do nothing
}
if (2 == position) {
try {
mBTSocket.getOutputStream().write(normalBoost.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(parent.getContext(), "DynaBoost control.", Toast.LENGTH_SHORT).show();
btnzero.setEnabled(false);
btnsix.setEnabled(false);
btntwelwe.setEnabled(false);
return; //do nothing
}
if (3 == position) {
try {
mBTSocket.getOutputStream().write(hardBoost.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(parent.getContext(), "DynaBoost control.", Toast.LENGTH_SHORT).show();
btnzero.setEnabled(false);
btnsix.setEnabled(false);
btntwelwe.setEnabled(false);
return; //do nothing
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
private class ReadInput implements Runnable {
private boolean bStop = false;
private Thread t;
public ReadInput() {
t = new Thread(this, "Input Thread");
t.start();
}
public boolean isRunning() {
return t.isAlive();
}
#Override
public void run() {
InputStream inputStream;
try {
inputStream = mBTSocket.getInputStream();
while (!bStop) {
byte[] buffer = new byte[256];
if (inputStream.available() > 0) {
inputStream.read(buffer);
int i = 0;
/*
* This is needed because new String(buffer) is taking the entire buffer i.e. 256 chars on Android 2.3.4 http://stackoverflow.com/a/8843462/1287554
*/
for (i = 0; i < buffer.length && buffer[i] != 0; i++) {
}
final String strInput = new String(buffer, 0, i);
/*
* If checked then receive text, better design would probably be to stop thread if unchecked and free resources, but this is a quick fix
*/
}
Thread.sleep(500);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void stop() {
bStop = true;
}
}
private class DisConnectBT extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... params) {//cant inderstand these dotss
if (mReadThread != null) {
mReadThread.stop();
while (mReadThread.isRunning())
; // Wait until it stops
mReadThread = null;
}
try {
mBTSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
mIsBluetoothConnected = false;
if (mIsUserInitiatedDisconnect) {
finish();
}
}
}
private void msg(String s) {
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
}
#Override
protected void onPause() {
if (mBTSocket != null && mIsBluetoothConnected) {
new DisConnectBT().execute();
}
Log.d(TAG, "Paused");
super.onPause();
}
#Override
protected void onResume() {
if (mBTSocket == null || !mIsBluetoothConnected) {
new ConnectBT().execute();
}
Log.d(TAG, "Resumed");
super.onResume();
}
#Override
protected void onStop() {
Log.d(TAG, "Stopped");
super.onStop();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
}
private class ConnectBT extends AsyncTask<Void, Void, Void> {
private boolean mConnectSuccessful = true;
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(Remote.this, "", "Connecting");// http://stackoverflow.com/a/11130220/1287554
}
#Override
protected Void doInBackground(Void... devices) {
try {
if (mBTSocket == null || !mIsBluetoothConnected) {
mBTSocket = mDevice.createInsecureRfcommSocketToServiceRecord(mDeviceUUID);
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
mBTSocket.connect();
}
} catch (IOException e) {
// Unable to connect to device`
// e.printStackTrace();
mConnectSuccessful = false;
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (!mConnectSuccessful) {
Toast.makeText(getApplicationContext(), "Could not connect.Please turn on Sound bar", Toast.LENGTH_LONG).show();
finish();
} else {
msg("Connected to Sound bar");
mIsBluetoothConnected = true;
mReadThread = new ReadInput(); // Kick off input reader
}
progressDialog.dismiss();
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
public void toggle( View View) //outside oncreate
{
if( overloadSwitch.isChecked() ){
try {
mBTSocket.getOutputStream().write(overloadOn.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return; //do nothing
}
else
{
try {
mBTSocket.getOutputStream().write(overloadOff.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return; //do nothing
}
}
}
#Override
public void run() {
InputStream inputStream;
try {
inputStream = mBTSocket.getInputStream();
byte[] buffer = new byte[1024];
inputStream.read(buffer);
int BTvalue = buffer;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Problem solved.
I spent late night yesterday with no succes. Angry and frustrated I went to bed. Today I found out that none of the codes I was trying didn`t work, because code was already there. Reading and writing to string. Just used the string and done :)
I am using csipsimple code and customised it to show brandname by getting json value from webservice . I am using SharedPreferences to store value .
Once the application is force closed , or device restart SharedPreferences are lost . I am using commit and clear but still the values are null .
BasePrefsWizard is the class responsible for pulling web data and DialerFragment is the other class i am calling the BrandName ( it is SavedBrand/ brand in code)
package com.mydial.wizards;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.preference.EditTextPreference;
import android.util.Base64;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.mydial.api.SipManager;
import com.mydial.api.SipProfile;
import com.mydial.db.DBProvider;
import com.mydial.models.Filter;
import com.mydial.ui.SipHome;
import com.mydial.ui.dialpad.DialerFragment;
import com.mydial.ui.filters.AccountFilters;
import com.mydial.ui.prefs.GenericPrefs;
import com.mydial.utils.AccountListUtils;
import com.mydial.utils.Log;
import com.mydial.utils.PreferencesProviderWrapper;
import com.mydial.utils.PreferencesWrapper;
import com.mydial.utils.AccountListUtils.AccountStatusDisplay;
import com.mydial.utils.animation.ActivitySwitcher;
import com.mydial.wizards.WizardUtils.WizardInfo;
import com.mydial.wizards.impl.Advanced;
import com.worldfone.R;
#SuppressLint("NewApi") public class BasePrefsWizard extends GenericPrefs {
public static final int SAVE_MENU = Menu.FIRST + 1;
public static final int TRANSFORM_MENU = Menu.FIRST + 2;
public static final int FILTERS_MENU = Menu.FIRST + 3;
public static final int DELETE_MENU = Menu.FIRST + 4;
private PreferencesProviderWrapper prefProviderWrapper;
private static final String THIS_FILE = "Base Prefs wizard";
protected SipProfile account = null;
private Button saveButton,cancel;
private String wizardId = "";
private WizardIface wizard = null;
private BroadcastReceiver mReceiver;
IntentFilter intentFilter;
public static final String myData = "mySharedPreferences";
public static String bal = null;
public static String sip = null;
public static String header = null;
public static String date = null;
public static String savedBal="";
public static String savedSip="";
public static String savedBrand="";
public static String webArray[] =new String[6];
#Override
protected void onCreate(Bundle savedInstanceState)
{
// Get back the concerned account and if any set the current (if not a
// new account is created)
Intent intent = getIntent();
long accountId = 1;
//intent.getLongExtra(SipProfile.FIELD_ID, SipProfile.INVALID_ID);
// TODO : ensure this is not null...
// setWizardId(intent.getStringExtra(SipProfile.FIELD_WIZARD));
setWizardId();
account = SipProfile.getProfileFromDbId(this, accountId, DBProvider.ACCOUNT_FULL_PROJECTION);
super.onCreate(savedInstanceState);
prefProviderWrapper = new PreferencesProviderWrapper(this);
// Bind buttons to their actions
cancel = (Button) findViewById(R.id.cancel_bt);
//cancel.setEnabled(false);
cancel.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
isOnline();
//saveAndFinish();
}
});
saveButton = (Button) findViewById(R.id.save_bt);
//saveButton.setEnabled(false);
saveButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
//setResult(RESULT_CANCELED, getIntent());
Intent intent = new Intent();
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
finish();
System.exit(0);
}
});
wizard.fillLayout(account);
loadValue();
}
public void isOnline()
{
ConnectivityManager connMgr = (ConnectivityManager) this
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
{
try
{
String webAccessNumberLink="http://myweblink.info/test/code.php?user=1234";
new webAccessNumber().execute(webAccessNumberLink);
}
catch(Exception e)
{
// System.out.println("exception in basepreference "+e);
}
}
else
{
// display error
showNetworkAlert();
}
}
void showNetworkAlert()
{
new AlertDialog.Builder(this)
.setTitle("Alert")
.setMessage(
"Please make sure you have Network Enabled")
.setNeutralButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
/*Intent siphome = new Intent(getApplicationContext(),SipHome.class);
startActivity(siphome);*/
}
}).show();
}
public void saveArray(String[] arrayOfweb)
{
int mode = Context.MODE_PRIVATE;
SharedPreferences mySharedPreferences =this.getSharedPreferences(myData,
mode);
SharedPreferences.Editor editor = mySharedPreferences.edit();
String f1 = arrayOfweb[0];
String f2 = arrayOfweb[1];
String f3 = arrayOfweb[2];
String f4 = arrayOfweb[3];
for(int i=0;i<arrayOfweb.length;i++)
{
}
//byMe added below to make preferences persistant
editor.clear();
editor.putString("balance",f1);
editor.putString("sipp",f2);
editor.putString("brand",f3);
editor.putString("prfx",f4);
editor.commit();
loadValue();
}
private void loadValue()
{
int mode = Context.MODE_PRIVATE;
SharedPreferences mySharedPreferences = this.getSharedPreferences(myData,
mode);
savedBal= mySharedPreferences.getString("balance", "");
savedSip = mySharedPreferences.getString("sipp", "");
savedBrand = mySharedPreferences.getString("barnd", "");
}
private boolean isResumed = false;
#Override
protected void onResume()
{
super.onResume();
isResumed = true;
updateDescriptions();
updateValidation();
//byMe
}
#Override
protected void onPause()
{
super.onPause();
isResumed = false;
//this.unregisterReceiver(this.mReceiver);
}
private boolean setWizardId()
{
try {
wizard=Advanced.class.newInstance();
// wizard = (WizardIface) wizardInfo.classObject.newInstance();
} catch (IllegalAccessException e) {
Log.e(THIS_FILE, "Can't access wizard class", e);
/*if (!wizardId.equals(WizardUtils.EXPERT_WIZARD_TAG)) {
return setWizardId(WizardUtils.EXPERT_WIZARD_TAG);
}*/
return false;
} catch (InstantiationException e) {
Log.e(THIS_FILE, "Can't access wizard class", e);
/* if (!wizardId.equals(WizardUtils.EXPERT_WIZARD_TAG)) {
return setWizardId(WizardUtils.EXPERT_WIZARD_TAG);
}
*/ return false;
}
//wizardId = wId;
wizard.setParent(this);
if(getSupportActionBar() != null) {
getSupportActionBar().setIcon(WizardUtils.getWizardIconRes(wizardId));
}
return true;
}
private boolean setWizardId(String wId) {
if (wizardId == null) {
return setWizardId(WizardUtils.EXPERT_WIZARD_TAG);
}
WizardInfo wizardInfo = WizardUtils.getWizardClass(wId);
if (wizardInfo == null) {
if (!wizardId.equals(WizardUtils.EXPERT_WIZARD_TAG)) {
return setWizardId(WizardUtils.EXPERT_WIZARD_TAG);
}
return false;
}
try {
wizard = (WizardIface) wizardInfo.classObject.newInstance();
} catch (IllegalAccessException e) {
Log.e(THIS_FILE, "Can't access wizard class", e);
if (!wizardId.equals(WizardUtils.EXPERT_WIZARD_TAG)) {
return setWizardId(WizardUtils.EXPERT_WIZARD_TAG);
}
return false;
} catch (InstantiationException e) {
Log.e(THIS_FILE, "Can't access wizard class", e);
if (!wizardId.equals(WizardUtils.EXPERT_WIZARD_TAG)) {
return setWizardId(WizardUtils.EXPERT_WIZARD_TAG);
}
return false;
}
wizardId = wId;
wizard.setParent(this);
if(getSupportActionBar() != null) {
getSupportActionBar().setIcon(WizardUtils.getWizardIconRes(wizardId));
}
return true;
}
#Override
protected void beforeBuildPrefs() {
// Use our custom wizard view
setContentView(R.layout.wizard_prefs_base);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if(isResumed) {
updateDescriptions();
updateValidation();
}
}
private void resolveStatus()
{
AccountStatusDisplay accountStatusDisplay = AccountListUtils
.getAccountDisplay(this, 1);
//status.setTextColor(accountStatusDisplay.statusColor);
//status.setText(accountStatusDisplay.statusLabel);
}
/**
* Update validation state of the current activity.
* It will check if wizard can be saved and if so
* will enable button
*/
public void updateValidation()
{
cancel.setEnabled(wizard.canSave());
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu)
{
// menu.findItem(SAVE_MENU).setVisible(wizard.canSave());
return super.onPrepareOptionsMenu(menu);
}
private static final int CHOOSE_WIZARD = 0;
private static final int MODIFY_FILTERS = CHOOSE_WIZARD + 1;
private static final int FINAL_ACTIVITY_CODE = MODIFY_FILTERS;
private int currentActivityCode = FINAL_ACTIVITY_CODE;
public int getFreeSubActivityCode()
{
currentActivityCode ++;
return currentActivityCode;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
}
/**
* Save account and end the activity
*/
public void saveAndFinish()
{
//this.registerReceiver(mReceiver, intentFilter);
saveAccount();
Intent intent = getIntent();
setResult(RESULT_OK, intent);
Intent it = new Intent(this,SipHome.class);
startActivity(it);
finish();
}
void updateStatus()
{
AccountStatusDisplay accountStatusDisplay = AccountListUtils
.getAccountDisplay(this, account.id);
}
/*
* Save the account with current wizard id
*/
private void saveAccount() {
saveAccount(wizardId);
}
#Override
protected void onDestroy() {
//byMe
super.onDestroy();
getSharedPreferences(WIZARD_PREF_NAME, MODE_PRIVATE).edit().clear().commit();
saveArray(webArray);
}
/**
* Save the account with given wizard id
* #param wizardId the wizard to use for account entry
*/
private void saveAccount(String wizardId) {
boolean needRestart = false;
PreferencesWrapper prefs = new PreferencesWrapper(getApplicationContext());
account = wizard.buildAccount(account);
account.wizard = wizardId;
if (account.id == SipProfile.INVALID_ID) {
// This account does not exists yet
prefs.startEditing();
wizard.setDefaultParams(prefs);
prefs.endEditing();
Uri uri = getContentResolver().insert(SipProfile.ACCOUNT_URI, account.getDbContentValues());
// After insert, add filters for this wizard
account.id = ContentUris.parseId(uri);
List<Filter> filters = wizard.getDefaultFilters(account);
if (filters != null) {
for (Filter filter : filters) {
// Ensure the correct id if not done by the wizard
filter.account = (int) account.id;
getContentResolver().insert(SipManager.FILTER_URI, filter.getDbContentValues());
}
}
// Check if we have to restart
needRestart = wizard.needRestart();
} else {
// TODO : should not be done there but if not we should add an
// option to re-apply default params
prefs.startEditing();
wizard.setDefaultParams(prefs);
prefs.endEditing();
getContentResolver().update(ContentUris.withAppendedId(SipProfile.ACCOUNT_ID_URI_BASE, account.id), account.getDbContentValues(), null, null);
}
// Mainly if global preferences were changed, we have to restart sip stack
if (needRestart) {
Intent intent = new Intent(SipManager.ACTION_SIP_REQUEST_RESTART);
sendBroadcast(intent);
}
}
#Override
protected int getXmlPreferences() {
return wizard.getBasePreferenceResource();
}
#Override
protected void updateDescriptions() {
wizard.updateDescriptions();
}
#Override
protected String getDefaultFieldSummary(String fieldName) {
return wizard.getDefaultFieldSummary(fieldName);
}
private static final String WIZARD_PREF_NAME = "Wizard";
#Override
public SharedPreferences getSharedPreferences(String name, int mode) {
return super.getSharedPreferences(WIZARD_PREF_NAME, mode);
}
private class webAccessNumber extends AsyncTask<String, Void, String>
{
//String balance;
ProgressDialog progressDialog;
#Override
protected String doInBackground(String... params) {
return getAccessNumber(params[0]);
}
#Override
protected void onPostExecute(String result)
{
if(result!=null)
{
try {
System.out.println("value of webAccessNumber "+result);
byte[] decoded = Base64.decode(result,Base64.DEFAULT);
String decodedStr =new String(decoded, "UTF-8");
//System.out.println(decodedStr);
JSONArray arr = new JSONArray(decodedStr);
//loop through each object
for (int i=0; i<arr.length(); i++)
{
JSONObject jsonObject = arr.getJSONObject(i);
bal = jsonObject.getString("balance");
sip = jsonObject.getString("server");
header = jsonObject.getString("brand");
webArray[1]=bal;
webArray[2]=sip;
webArray[3]=barnd;
saveArray(webArray);
saveAndFinish();
progressDialog.dismiss();
}
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
progressDialog = new ProgressDialog(BasePrefsWizard.this);
progressDialog.setMessage("Loading..............");
progressDialog.setIndeterminate(false);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setCancelable(true);
progressDialog.show();
}
#Override
protected void onProgressUpdate(Void... values) {
}
public String getAccessNumber(String b) {
String balance = "";
String currency = "USD";
try {
balance = DownloadText(b).trim();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return balance;
}
String DownloadText(String URL) {
int BUFFER_SIZE = 2000;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return "";
}
InputStreamReader isr = new InputStreamReader(in);
int charRead;
String str = "";
char[] inputBuffer = new char[BUFFER_SIZE];
try {
while ((charRead = isr.read(inputBuffer)) > 0) {
String readString = String.copyValueOf(inputBuffer, 0,
charRead);
str += readString;
inputBuffer = new char[BUFFER_SIZE];
}
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
return str;
}
InputStream OpenHttpConnection(String urlString) throws IOException {
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
} catch (Exception ex) {
throw new IOException("Error connecting");
}
return in;
}
}//end of webAccessNumber asynchronus
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0)
{
isOnline();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
You should not clear the SharedPreferences in the onDestroy() method, because when you run your activity or your application again, all the saved values and variables in preferences are deleted, ( like you installed your application for the first time).
PS : here is a tutorial about Using SharedPreferences and Storing Data in Android
You are clearing your preferences in your code,
#Override
protected void onDestroy() {
//byMe
super.onDestroy();
//Preferences cleared
getSharedPreferences(WIZARD_PREF_NAME, MODE_PRIVATE).edit().clear().commit();
saveArray(webArray);
}
This is clearing your preferences.
You are clearing the shared prefereence in onDestroy:
#Override
protected void onDestroy() {
//byMe
super.onDestroy();
getSharedPreferences(WIZARD_PREF_NAME, MODE_PRIVATE).edit().clear().commit(); // <-- Remove this
saveArray(webArray);
}
You delete it in:
#Override
protected void onDestroy() {
super.onDestroy();
getSharedPreferences(WIZARD_PREF_NAME, MODE_PRIVATE).edit().clear().commit();
saveArray(webArray);
}
Also see this http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle
I have my major project on android based home automation system meaning that I have to control home appliances using android bluetooth. I am using HC-05 bluetooth module which receives the string sent to it through my application, sends it to PIC16f877a and the pic in turn depending upon the string received, controls the appliances. Now my problem is that I have been able to pair and connect the devices through my application but my application is not sending the characters which I want to send when I click the button. Note that PIC and the Bluetooth module are working fine. please help me. I am posting my code below hope you guys won't mind.
package com.chainedcat.splashscreen;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
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.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivityActivity extends Activity{
private BluetoothAdapter BA;
private ArrayList<BluetoothDevice> devices;
private ListView lv;
private TextView text;
private BluetoothSocket btSocket=null;
private ArrayAdapter<String> btArrayAdapter;
private static final int REQUEST_ENABLE_BT = 1;
private UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34EB");
private OutputStream outStream=null;
public void Init(){
BA = BluetoothAdapter.getDefaultAdapter();
text =(TextView) findViewById(R.id.text);
lv = (ListView) findViewById(R.id.listView1);
devices = new ArrayList<BluetoothDevice>();
btArrayAdapter= new ArrayAdapter<String>this,android.R.layout.simple_list_item_1);
lv.setAdapter(btArrayAdapter);
}
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
Init();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
BluetoothDevice selectedDevice = devices.get(arg2);
if(selectedDevice.getBondState()== BluetoothDevice.BOND_NONE){
pairDevice(selectedDevice);
}
else if(selectedDevice.getBondState()==BluetoothDevice.BOND_BONDED){
connect(selectedDevice);
}
}
});
}
public void bluetooth(View view){
if(!BA.isEnabled()){
Intent btIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(btIntent, REQUEST_ENABLE_BT);
Toast.makeText(getApplicationContext(), "Bluetooth turned on!!", Toast.LENGTH_LONG).show();
btExtra();
}else{
Toast.makeText(getApplicationContext(), "Bluetooth is already on!!", Toast.LENGTH_LONG).show();
btExtra();
}
}
public void btExtra(){
btArrayAdapter.clear();
BA.startDiscovery();
registerReceiver(btReceiver, new tentFilter(BluetoothDevice.ACTION_FOUND));
}
final BroadcastReceiver btReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)){
BluetoothDevice device=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
devices.add(device);
String status=null;
if(device.getBondState()==BluetoothDevice.BOND_BONDED){
status="paired";
}else{status="not paired";}
btArrayAdapter.add(device.getName()+" : "+status+"\n"+device.getAddress());
btArrayAdapter.notifyDataSetChanged();
}
}
};
#Override
protected void onActivityResult(int requestCode,int resultCode, Intent data){
if(requestCode==REQUEST_ENABLE_BT){
if(BA.isEnabled()){
text.setText("Bluetooth Status:Enabled");
}else{
text.setText("Bluetooth Status:Disabled");
}
}
}
private void pairDevice(BluetoothDevice device) {
Method m=null;
try {
m = device.getClass().getMethod("createBond", (Class[]) null);
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
m.invoke(device, (Object[]) null);
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
connect(device);
}
public void connect(BluetoothDevice device){
Toast.makeText(getApplicationContext(), "connecting....", Toast.LENGTH_LONG).show();
try {
btSocket=device.createInsecureRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BA.cancelDiscovery();
try {
Toast.makeText(getApplicationContext(), "entered in run", Toast.LENGTH_LONG).show();
btSocket.connect();
if(btSocket!=null){btSocket.close();}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void send(String s){
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] bytes = s.getBytes();
try {
outStream.write(bytes);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void fan(View v){
send("f");
}
#Override
public void onDestroy(){
super.onDestroy();
BA.disable();
unregisterReceiver(btReceiver);
}
}
I have done an android application for a simple chat application.I am using command prompt as server and chat is done with emulator as client.This application is not working when we put the apk in phone using WIFI. Android client program is shown below
package edu.UTEP.android;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class AndyChatActivity extends Activity {
private Handler handler = new Handler();
public ListView msgView;
public ArrayAdapter<String> msgList;
// public ArrayAdapter<String> msgList=new ArrayAdapter<String>(this,
// android.R.layout.simple_list_item_1);;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
msgView = (ListView) findViewById(R.id.listView);
msgList = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1);
msgView.setAdapter(msgList);
// msgView.smoothScrollToPosition(msgList.getCount() - 1);
Button btnSend = (Button) findViewById(R.id.btn_Send);
receiveMsg();
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(AndyChatActivity.this, "here", Toast.LENGTH_SHORT).show();
final EditText txtEdit = (EditText) findViewById(R.id.txt_inputText);
String msg=txtEdit.getText().toString();
Toast.makeText(AndyChatActivity.this, msg, Toast.LENGTH_SHORT).show();
//msgList.add(txtEdit.getText().toString());
sendMessageToServer(txtEdit.getText().toString());
msgView.smoothScrollToPosition(msgList.getCount() - 1);
}
});
//receiveMsg();
//----------------------------
//server msg receieve
//-----------------------
//End Receive msg from server//
}
public void sendMessageToServer(String str) {
final String str1=str;
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
//String host = "https://www.tudens.in";
String host="192.168.1.5";
//Toast.makeText(AndyChatActivity.this, "thread Opened", Toast.LENGTH_SHORT).show();
//String host2 = "127.0.0.1";
PrintWriter out;
try {
Socket socket = new Socket(host, 8008);
out = new PrintWriter(socket.getOutputStream());
Log.d("1", "good");
// out.println("hello");
out.println(str1);
Log.d("2", "gd");
out.flush();
Log.d("", "hello");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("", "hello222");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("", "hello4333");
}
}
}).start();
}
public void receiveMsg()
{
new Thread(new Runnable()
{
#Override
public void run() {
// TODO Auto-generated method stub
final String host="192.168.1.5";
//final String host="10.0.2.2";
//final String host="localhost";
Socket socket = null ;
BufferedReader in = null;
try {
socket = new Socket(host,8008);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while(true)
{
String msg = null;
try {
msg = in.readLine();
Log.d("","MSGGG: "+ msg);
//msgList.add(msg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(msg == null)
{
break;
}
else
{
displayMsg(msg);
}
}
}
}).start();
}
public void displayMsg(String msg)
{
final String mssg=msg;
handler.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
msgList.add(mssg);
msgView.setAdapter(msgList);
msgView.smoothScrollToPosition(msgList.getCount() - 1);
Log.d("","hi");
}
});
}
}
java server program is shown below :
import java.io.*;
import java.net.*;
import java.util.*;
/**
* A simple chat server implemented using TCP/IP sockets. A client can
* connect to this server and send messages to other clients. The chat
* server receives messages from clients and broadcast them to all the
* connected clients. A message is an arbitrary text and is also
* printed on stdout. The default port number is 8008.
*
* <pre>
* Usage: java ChatServer
* </pre>
*
* #author Yoonsik Cheon
*/
public class ChatServer {
private static final String USAGE = "Usage: java ChatServer";
/** Default port number on which this server to be run. */
private static final int PORT_NUMBER = 8008;
/** List of print writers associated with current clients,
* one for each. */
private List<PrintWriter> clients;
/** Creates a new server. */
public ChatServer() {
clients = new LinkedList<PrintWriter>();
}
/** Starts the server. */
public void start() {
System.out.println("AndyChat server started on port "
+ PORT_NUMBER + "!");
try {
ServerSocket s = new ServerSocket(PORT_NUMBER);
for (;;) {
Socket incoming = s.accept();
new ClientHandler(incoming).start();
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("AndyChat server stopped.");
}
/** Adds a new client identified by the given print writer. */
private void addClient(PrintWriter out) {
synchronized(clients) {
clients.add(out);
}
}
/** Adds the client with given print writer. */
private void removeClient(PrintWriter out) {
synchronized(clients) {
clients.remove(out);
}
}
/** Broadcasts the given text to all clients. */
private void broadcast(String msg) {
for (PrintWriter out: clients) {
out.println(msg);
out.flush();
}
}
public static void main(String[] args) {
if (args.length > 0) {
System.out.println(USAGE);
System.exit(-1);
}
new ChatServer().start();
}
/** A thread to serve a client. This class receive messages from a
* client and broadcasts them to all clients including the message
* sender. */
private class ClientHandler extends Thread {
/** Socket to read client messages. */
private Socket incoming;
/** Creates a hander to serve the client on the given socket. */
public ClientHandler(Socket incoming) {
this.incoming = incoming;
}
/** Starts receiving and broadcasting messages. */
public void run() {
PrintWriter out = null;
try {
out = new PrintWriter(
new OutputStreamWriter(incoming.getOutputStream()));
// inform the server of this new client
ChatServer.this.addClient(out);
out.print("Welcome to AndyChat! ");
out.println("Enter BYE to exit.");
out.flush();
BufferedReader in
= new BufferedReader(
new InputStreamReader(incoming.getInputStream()));
for (;;) {
String msg = in.readLine();
if (msg == null) {
break;
} else {
if (msg.trim().equals("BYE"))
break;
System.out.println("Received: " + msg);
// broadcast the receive message
ChatServer.this.broadcast(msg);
}
}
incoming.close();
ChatServer.this.removeClient(out);
} catch (Exception e) {
if (out != null) {
ChatServer.this.removeClient(out);
}
e.printStackTrace();
}
}
}
}
You have to change your host address to 10.0.2.2. Because for android emulators host address are different. You can read more about it here.
I'm getting a NullPointerException at the line :
handler.getQueryResponse(stream);
I've looked over the source code quite a few times and I'm not sure exactly why this is occurring.
Any suggestions are greatly appreciated.
LOGCAT:
08-16 16:26:24.401: E/AndroidRuntime(9542): FATAL EXCEPTION: main
08-16 16:26:24.401: E/AndroidRuntime(9542): java.lang.NullPointerException
08-16 16:26:24.401: E/AndroidRuntime(9542): at com.project.new.datasettings.UpdateActivity.success(UpdateActivity.java:426)
08-16 16:26:24.401: E/AndroidRuntime(9542): at com.project.new.datasettings.UpdateActivity$NetworkTask.onPostExecute(UpdateActivity.java:389)
08-16 16:26:24.401: E/AndroidRuntime(9542): at com.project.new.datasettings.UpdateActivity$NetworkTask.onPostExecute(UpdateActivity.java:1)
SOURCE:
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.zip.GZIPInputStream;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLException;
import javax.xml.parsers.ParserConfigurationException;
import com.project.new.datasettings.XmlParserHandlerFinal;
import org.xml.sax.SAXException;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.ClipDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.os.StrictMode;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import com.project.new.datasettings.R;
public class UpdateActivity extends Activity implements OnClickListener {
public static ArrayList<String> NameArr = new ArrayList<String>();
public static ArrayList<String> ValueArr = new ArrayList<String>();
public static ArrayList<String> nameArr = new ArrayList<String>();
public static ArrayList<String> ApnArr = new ArrayList<String>();
public static ArrayList<String> mmscArr = new ArrayList<String>();
public static ArrayList<String> mmsportArr = new ArrayList<String>();
public static ArrayList<String> mmsproxyArr = new ArrayList<String>();
public static ArrayList<String> portArr = new ArrayList<String>();
public static ArrayList<String> proxyArr = new ArrayList<String>();
private ImageView mProgressImageview1;
private ImageView mProgressImageview2;
private ImageView mProgressImageview3;
private ImageView mProgressImageview4;
private ImageView mProgressImageview5;
public static int count;
AlertDialog mErrorAlert = null;
int version;
public static int TotalSteps = 8;
private TelephonyManager tm;
private static final String LOG_TAG = "STDataSettings";
private Button mUpdateButton = null;
private Button mAssistUpdateButton = null;
private Button mAssistInstrButton = null;
private TextView mReadAgainButton = null;
private int mInstructionNumber = 0;
AlertDialog mConfirmAlert = null;
public static InputStream stream = null;
public static XmlParserHandlerFinal handler;
private NetworkTask task;
private AnimationDrawable loadingAnimation;
private static final String TAG = "UpdateActivity";
Context ctx;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
int networkType = tm.getNetworkType();
int phoneType = tm.getPhoneType();
int version = android.os.Build.VERSION.SDK_INT;
if (phoneType == TelephonyManager.PHONE_TYPE_CDMA
|| (phoneType != TelephonyManager.PHONE_TYPE_GSM
&& networkType != TelephonyManager.NETWORK_TYPE_GPRS
&& networkType != TelephonyManager.NETWORK_TYPE_EDGE
&& networkType != TelephonyManager.NETWORK_TYPE_HSDPA
&& networkType != TelephonyManager.NETWORK_TYPE_HSPA
&& networkType != TelephonyManager.NETWORK_TYPE_HSPAP
&& networkType != TelephonyManager.NETWORK_TYPE_HSUPA
&& networkType != TelephonyManager.NETWORK_TYPE_UMTS && networkType != TelephonyManager.NETWORK_TYPE_LTE)) {
// If the phone type is CDMA or
// the phone phone type is not GSM and the network type is none of
// the network types indicated in the statement
// Display incompatibility message
showAlert(getString(R.string.incomp_sm_dialog));
// Network type is looked because some tablets have no phone type.
// We rely on network type in such cases
} else if (!(tm.getSimState() == TelephonyManager.SIM_STATE_ABSENT
|| (tm.getSimOperator())
.equals(getString(R.string.numeric_tmo)) || (tm
.getSimOperator()).equals(getString(R.string.numeric_att)))) {
// if SIM is present and is NOT a T-Mo network SIM,
// display Error message alert indicating to use SM SIM
showAlert(getString(R.string.insert_sm_dialog));
}// No SIM or SIM with T-Mo MNC MCC present
else if (version < VERSION_CODES.ICE_CREAM_SANDWICH) {
// Initial UI setup for versions lower than ICS
setContentView(R.layout.update);
mUpdateButton = (Button) findViewById(R.id.update_button);
mUpdateButton.setOnClickListener(this);
} else {// ICS and up
// task.execute();
if ((tm.getSimOperator()).equals(getString(R.string.numeric_tmo))
|| (tm.getSimOperator())
.equals(getString(R.string.numeric_att))) {
task = new NetworkTask();
task.execute("");
// Device has T-Mo network SIM card MCC and MNC correctly
// populated
// Reduce number of steps to 6
TotalSteps = 6;
}
}
}
public void onClick(View v) {
if (v == mUpdateButton) {
// Update button for versions lower than ICS is selected
// setContentView(R.layout.updating);
onClickMethod(v);
Intent i = new Intent(this, ConfigFinalActivity.class);
startActivity(i);
finish();
} else if (v == mAssistUpdateButton) {
// Update button for ICS and up is selected
// Get the TextView in the Assist Update UI
TextView tv = (TextView) findViewById(R.id.apn_app_text_cta2);
String text = "";
CharSequence styledText = text;
switch (mInstructionNumber) {
case 0:
// Retrieve the instruction string resource corresponding the
// 2nd set of instructions
text = String.format(getString(R.string.apn_app_text_instr),
TotalSteps);
styledText = Html.fromHtml(text);
// Update the TextView with the correct set of instructions
tv.setText(styledText);
// Increment instruction number so the correct instructions
// string resource can be retrieve the next time the update
// button is pressed
mInstructionNumber++;
break;
case 1:
text = getString(R.string.apn_app_text_instr2);
styledText = Html.fromHtml(text);
tv.setText(styledText);
// Increment instruction number so the correct instructions
// string resource can be retrieve the next time the update
// button is pressed
mInstructionNumber++;
break;
case 2:
// Final set of instructions-Change to the corresponding layout
setContentView(R.layout.assist_instructions);
String assistUpdateInstr = String.format(
getString(R.string.apn_app_text_instr3), TotalSteps);
styledText = Html.fromHtml(assistUpdateInstr);
TextView assistInstrText = (TextView) findViewById(R.id.updated_text);
assistInstrText.setText(styledText);
mAssistInstrButton = (Button) findViewById(R.id.assist_instr_btn);
mReadAgainButton = (TextView) findViewById(R.id.read_again_btn);
mAssistInstrButton.setOnClickListener(this);
mReadAgainButton.setOnClickListener(this);
}
} else if (v == mAssistInstrButton) {
// "LET'S DO THIS" Button in final instructions screen for ICS and
// up is selected
// Create ConfigActivity Intent
Intent i = new Intent(this, ConfigFinalActivity.class);
// Invoke ConfigActivity Intent to start the assisted update
startActivity(i);
finish();
} else if (v == mReadAgainButton) {
// go back to 1st set of instructions if read again is selected
mInstructionNumber = 0;
setContentView(R.layout.assist_update);
String assistUpdate = getString(R.string.apn_app_text_cta2);
CharSequence styledText = Html.fromHtml(assistUpdate);
TextView assistText = (TextView) findViewById(R.id.apn_app_text_cta2);
assistText.setText(styledText);
mAssistUpdateButton = (Button) findViewById(R.id.assist_update_btn);
mAssistUpdateButton.setOnClickListener(this);
}
}
public void onClickMethod(View v) {
mUpdateButton = (Button) findViewById(R.drawable.btn_update_active_hdpi);
}
private void showAlert(String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(message).setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
UpdateActivity.this.finish();
}
});
mConfirmAlert = builder.create();
mConfirmAlert.show();
}
// AsyncTask to call web service
class NetworkTask extends AsyncTask<String, Integer, InputStream> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected InputStream doInBackground(String... params) {
try {
// saving the response in InputStream
stream = getQueryResults("https://dl.dropboxusercontent.com/u/31771876/GetPhoneSettings-ST-rsp-eng.xml");
// stream = new BufferedInputStream(https.getInputStream());
DataInputStream in = new DataInputStream(stream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) { // Print the content on the console
System.out.println (strLine);
System.out.println (strLine);
in.close();
}
} catch (IOException e) {
Log.v(LOG_TAG, e.toString());
e.printStackTrace();
} catch (SAXException e) {
Log.v(LOG_TAG, e.toString());
e.printStackTrace();
} catch (Exception e) {
Log.v(LOG_TAG, e.toString());
e.printStackTrace();
}
// The code below plays a Simple Promo animation
for (int incr = 0; incr < 2; incr++) {
// Sleep for 1/2 second
// Invoke UI to change updating text to show 1 dot
// And Increasing the level to reduce the amount of clipping and
// slowly reveals the hand image
publishProgress(R.drawable.loading_full,
R.drawable.loading_empty, R.drawable.loading_empty,
R.drawable.loading_empty, R.drawable.loading_empty);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.d(TAG, "sleep failure");
}
publishProgress(R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_empty,
R.drawable.loading_empty, R.drawable.loading_empty);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.d(TAG, "sleep failure");
}
publishProgress(R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_full,
R.drawable.loading_empty, R.drawable.loading_empty);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.d(TAG, "sleep failure");
}
publishProgress(R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_empty);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.d(TAG, "sleep failure");
}
publishProgress(R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_full);
// Sleep for 1/2 second
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.d(TAG, "sleep failure");
}
}
return stream;
}
/*
* Sends a query to server and gets back the parsed results in a bundle
* urlQueryString - URL for calling the webservice
*/
protected synchronized InputStream getQueryResults(String urlQueryString)
throws IOException, SAXException, SSLException,
SocketTimeoutException, Exception {
// HttpsURLConnection https = null;
HttpsURLConnection https = null;
String uri = urlQueryString;
URL urlo = new URL(uri);
try {
https = (HttpsURLConnection) urlo.openConnection();
https.setConnectTimeout(20000); // 20 second timeout
https.setRequestProperty("Connection", "Keep-Alive");
if ("gzip".equals(https.getContentEncoding())) {
stream = new GZIPInputStream(stream);
} else
stream = https.getInputStream();
} catch (SSLException e) {
Log.e(LOG_TAG, e.toString());
e.printStackTrace();
} catch (SocketTimeoutException e) {
Log.e(LOG_TAG, e.toString());
e.printStackTrace();
} catch (IOException e) {
Log.e(LOG_TAG, e.toString());
e.printStackTrace();
} catch (Exception e) {
Log.e(LOG_TAG, e.toString());
e.printStackTrace();
} finally {
// https.disconnect();
}
return stream;
}
#Override
protected void onProgressUpdate(Integer... progress) {
// Call function to update image view
setProgressImgView(progress[0], progress[1], progress[2], progress[3], progress[4]);
}
#Override
protected void onPostExecute(InputStream stream) {
super.onPostExecute(stream);
// This method is called to parse the response and save the ArrayLists
success();
}
}
private void setProgressImgView(Integer imageViewId1, Integer imageViewId2, Integer imageViewId3, Integer imageViewId4, Integer imageViewId5) {
// update image view with the updating dots
// Reset view layout in case orientation while updating
setContentView(R.layout.updating);
mProgressImageview1 = (ImageView) findViewById(R.id.loading_empty1);
mProgressImageview1.setBackgroundResource(imageViewId1);
mProgressImageview2 = (ImageView) findViewById(R.id.loading_empty2);
mProgressImageview1.setBackgroundResource(imageViewId2);
mProgressImageview3 = (ImageView) findViewById(R.id.loading_empty3);
mProgressImageview1.setBackgroundResource(imageViewId3);
mProgressImageview4 = (ImageView) findViewById(R.id.loading_empty4);
mProgressImageview1.setBackgroundResource(imageViewId4);
mProgressImageview5 = (ImageView) findViewById(R.id.loading_empty5);
mProgressImageview1.setBackgroundResource(imageViewId5);
}
#Override
protected void onRestart() {
super.onRestart();
if (mErrorAlert != null)
mErrorAlert.dismiss();
}
public void success() {
// to parse the response
try {
handler.getQueryResponse(stream);
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// to set method to save the ArryaLists from the parser
setArrayList();
Intent i = new Intent(this, ConfigFinalActivity.class);
startActivity(i);
finish();
}
// method to save the ArrayLists from parser
public static void setArrayList() {
nameArr = handler.getnameArr();
ApnArr = handler.getApnArr();
mmscArr = handler.getMMSCArr();
mmsproxyArr = handler.getMmscProxyArr();
mmsportArr = handler.getMmsPortArr();
proxyArr = handler.getMmscProxyArr();
portArr = handler.getMmsPortArr();
count = handler.getCount();
//System.out.println("testing123");
for(int i = 0; i < nameArr.size()-1; i++){
System.out.println(nameArr.get(i));
}
for(int i = 0; i < ApnArr.size()-1; i++){
System.out.println(ApnArr.get(i));
}
}
}
XMLPARSERHANDLERFINAL:
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import android.content.ContentValues;
import android.content.Context;
import android.os.StrictMode;
import android.util.Log;
public class XmlParserHandlerFinal extends DefaultHandler {
public String queryResult;
private String name, Value;
public ArrayList<String> NameArr = new ArrayList<String>();
public ArrayList<String> ValueArr = new ArrayList<String>();
public ArrayList<String> nameArr = new ArrayList<String>();
public ArrayList<String> ApnArr = new ArrayList<String>();
public ArrayList<String> mmscArr = new ArrayList<String>();
public ArrayList<String> mmsportArr = new ArrayList<String>();
public ArrayList<String> mmsproxyArr = new ArrayList<String>();
public ArrayList<String> portArr = new ArrayList<String>();
public ArrayList<String> proxyArr = new ArrayList<String>();
public ArrayList<ContentValues> ArrValues = new ArrayList<ContentValues>();
public ContentValues values = new ContentValues();
public int count = 0;
Context c;
private boolean isPhoneSettings = false, isName = false, isValue = false;;
public XmlParserHandlerFinal() {
}
public void setContext(Context c) {
this.c = c;
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes atts) {
if (qName.equalsIgnoreCase("Phonesettings")) {
isPhoneSettings = true;
}
if (qName.equals("name")) {
isName = true;
}
if (qName.equals("value")) {
isValue = true;
}
}
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (isPhoneSettings) {
isPhoneSettings = false;
}
if (isName) {
isName = false;
}
if (isValue) {
isValue = false;
}
}
public void characters(char ch[], int start, int length)
throws SAXException {
if (isName) {
name = new String(ch, start, length);
NameArr.add(name);
}
if (isValue) {
Value = new String(ch, start, length);
ValueArr.add(Value);
values.put(name, Value);
if (name.equals("name")) {
nameArr.add(Value);
} else if (name.equals("apn")) {
ApnArr.add(Value);
} else if (name.equals("mmsc")) {
count++;
mmscArr.add(Value);
} else if (name.equals("mmsproxy")) {
mmsproxyArr.add(Value);
} else if (name.equals("mmsport")) {
mmsportArr.add(Value);
} else if (name.equals("port")) {
portArr.add(Value);
} else if (name.equals("proxy")) {
proxyArr.add(Value);
} else
if (name.equals("type")) {
// System.out.println("values in parser" + values);
ArrValues.add(values);
Log.v("value", Value);
System.out.println("size " + ArrValues.size());
// ((ConfigActivityForMultiProf) context)
// .InsertAPN();
// try {
// ((ConfigActivityForMultiProf) context)
// .showNotification(values);
// } catch (ParserConfigurationException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
/*
* for(int i =0;i<=NameArr.size()-1;i++){ NameArr.remove(i); }
* for(int i =0;i<=ValueArr.size()-1;i++){ ValueArr.remove(i); }
*/
}
}
}
public String getQueryResponse(InputStream in) throws SAXException,
IOException {
try {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
SAXParserFactory spf = SAXParserFactory.newInstance();
Log.v("In the parser", "now");
SAXParser sp;
sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
xr.setContentHandler(this);
xr.parse(new InputSource(in));
} catch (ParserConfigurationException e) {
Log.e("", "XML Handler Exception: " + e.toString());
}
return queryResult;
}
public int getCount() {
return count;
}
public ArrayList<String> getNameArr() {
for (int i = 0; i <= NameArr.size() - 1; i++) {
System.out.println(NameArr.get(i));
}
return NameArr;
}
public ArrayList<String> getValueArr() {
for (int i = 0; i <= ValueArr.size() - 1; i++) {
System.out.println(ValueArr.get(i));
}
return ValueArr;
}
public ArrayList<String> getnameArr() {
for (int i = 0; i <= nameArr.size() - 1; i++) {
System.out.println(nameArr.get(i));
}
return nameArr;
}
public ArrayList<String> getApnArr() {
for (int i = 0; i <= ApnArr.size() - 1; i++) {
System.out.println(ApnArr.get(i));
}
return ApnArr;
}
public ArrayList<String> getMMSCArr() {
return mmscArr;
}
public ArrayList<String> getMmscProxyArr() {
return mmsproxyArr;
}
public ArrayList<String> getMmsPortArr() {
return mmsportArr;
}
public ArrayList<String> getProxyArr() {
return proxyArr;
}
public ArrayList<String> getPortArr() {
return portArr;
}
public ArrayList<ContentValues> getArrValuesArr() {
return ArrValues;
}
}
Your declaration of handler still needs to assign it a value before reference. Just because the declaration is static, does not mean that the variable is referencing anything.
Here is a simpler example of what you are trying to do:
public class MyClass {
public static Object o;
public static void main(String[] args) {
String s;
s = o.toString(); // this will throw an exception
}
}
You still need to initialize the data member. You can use a static initialization block as one method. Example:
public class MyClass {
public static Object o;
static {
o = new Object(); // initialize the data member here
}
public static void main(String[] args) {
String s;
s = o.toString(); // now pointing to a valid object
}
}