I have an AsyncTask method titled "NetworkTask" which is supposed to query a web service and start a loading animation however the animation never starts and when I set a breakpoint at the line:
private class NetworkTask extends AsyncTask<String, Integer, InputStream> {
I never seem to reach the method NetworkTask and I'm unsure why this might be happening.
Any insight/input as to what might be causing this issue is greatly appreciated.
SOURCE:
public class UpdateActivity extends Activity {
private TelephonyManager tm;
AlertDialog mConfirmAlert = null;
NetworkTask task;
ImageView image, text;
AlertDialog mErrorAlert = null;
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>();
public static int count;
public AnimationDrawable mTextAnimation = null;
TextView mUpdatetext;
public static InputStream stream = null;
int version;
public static BigInteger iD1, iD2, mdN1, mdN2;
BigInteger[] id, mdnId;
public static String ICCID, MDN;
public static String caR;
public static int result;
private static final String LOG_TAG = "DataSettings";
public static final String Base_URL = "https://sitwapgate.example.com/REST/phoneSettings";
public static XmlParserHandlerFinal handler;
public static int TotalSteps = 8;
public FileInputStream fis;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// instance for xml parser class
handler = new XmlParserHandlerFinal();
handler.setContext(this.getBaseContext());
tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
int networkType = tm.getNetworkType();
int phoneType = tm.getPhoneType();
version = android.os.Build.VERSION.SDK_INT;
// to get MDN(MCC+MNC) of the provider of the SIM and ICCID (Serial
// number of the SIM)
// and to check for the Carrier type
getImpVariablesForQuery();
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 or ATT 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 & ATT MNC MCC present
else if ((tm.getSimOperator()).equals(getString(R.string.numeric_tmo))
|| (tm.getSimOperator())
.equals(getString(R.string.numeric_att))) {
// Device has T-Mo or ATT network SIM card MCC and MNC correctly
// populated
TotalSteps = 6;
setContentView(R.layout.updating);
// AsyncTask to call the web service
task = new NetworkTask();
task.execute("");
}
}
private void getImpVariablesForQuery() {
long d = 1234;
BigInteger divisor = BigInteger.valueOf(d);
// to get MDN
MDN = tm.getLine1Number();
// MDN = "7862125102";
if (MDN.equals("")) {
mdN1 = null;
mdN2 = null;
} else {
Log.d("MDN", MDN);
BigInteger bInt = new BigInteger(MDN);
mdnId = bInt.divideAndRemainder(divisor);
// to retrieve ICCID number of the SIM
mdN1 = mdnId[1];
System.out.println("MDN%1234 = " + mdN1);
mdN2 = mdnId[0];
System.out.println("MDN/1234 = " + mdN2);
}
ICCID = tm.getSimSerialNumber();
if (ICCID.equals("")) {
iD1 = null;
iD2 = null;
} else {
Log.d("ICCID", ICCID);
BigInteger bInteger = new BigInteger(ICCID);
id = bInteger.divideAndRemainder(divisor);
iD1 = id[1];
System.out.println("ICCID%1234 = " + iD1);
iD2 = id[0];
System.out.println("ICCID/1234 = " + iD2);
}
// Check for the Carrier Type
if ((tm.getSimOperator()).equals(getString(R.string.numeric_tmo))) {
caR = "TMO";
} else if ((tm.getSimOperator())
.equals(getString(R.string.numeric_att))) {
caR = "ATT";
}
}
// AsyncTask to call web service
private class NetworkTask extends AsyncTask<String, Integer, InputStream> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected InputStream doInBackground(String... params) {
try {
Log.i("url...", Base_URL);
stream = getQueryResults(Base_URL);
} 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();
}
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;
try {
String uri = urlQueryString;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
BasicNameValuePair mdn1, mdn2,id1,id2;
if (MDN.equals("")) {
mdn1 = new BasicNameValuePair("mdn1", null);
mdn2 = new BasicNameValuePair("mdn2", null);
} else {
mdn1 = new BasicNameValuePair("mdn1", mdN1.toString());
mdn2 = new BasicNameValuePair("mdn2", mdN2.toString());
}
BasicNameValuePair car = new BasicNameValuePair("car", caR);
if (ICCID.equals("")) {
id1 = new BasicNameValuePair("id1", null);
id2 = new BasicNameValuePair("id2", null);
} else {
id1 = new BasicNameValuePair("id1",
iD1.toString());
id2 = new BasicNameValuePair("id2",
iD2.toString());
}
nameValuePairs.add(mdn1);
nameValuePairs.add(mdn2);
nameValuePairs.add(car);
nameValuePairs.add(id1);
nameValuePairs.add(id2);
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(
nameValuePairs, "ISO-8859-1");
KeyStore trustStore = KeyStore.getInstance(KeyStore
.getDefaultType());
trustStore.load(null, null);
SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory
.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443));
ClientConnectionManager ccm = new ThreadSafeClientConnManager(
params, registry);
HttpClient httpClient = new DefaultHttpClient(ccm, params);
params = httpClient.getParams();
HttpClientParams.setRedirecting(params, true);
HttpPost httpPost = new HttpPost(uri);
httpPost.addHeader("Authorization",
getB64Auth("nmundru", "abc123"));
httpPost.setHeader("Content-Type", "text/plain; charset=utf-8");
Log.v("httpPost", httpPost.toString());
httpPost.setEntity(urlEncodedFormEntity);
HttpResponse httpResponse = httpClient.execute(httpPost);
System.out.println("response...." + httpResponse.toString());
Log.v("response...", httpResponse.toString());
stream = httpResponse.getEntity().getContent();
// save the InputStream in a file
try {
FileOutputStream fOut = openFileOutput("settings.xml",
Context.MODE_WORLD_READABLE);
DataInputStream in = new DataInputStream(stream);
BufferedReader br = new BufferedReader(
new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
System.out.println(strLine); //to print the response
// in logcat
fOut.write(strLine.getBytes());
}
fOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
fis = openFileInput("settings.xml");
} catch (Exception e) {
Log.e(LOG_TAG, e.toString());
// e.printStackTrace();
tryagain();
} finally {
// https.disconnect();
}
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
}
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
}
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
}
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
}
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
}
return stream;
}
private String getB64Auth(String login, String pass) {
String source = login + ":" + pass;
String ret = "Basic "
+ Base64.encodeToString(source.getBytes(), Base64.URL_SAFE
| Base64.NO_WRAP);
return ret;
}
#Override
protected void onProgressUpdate(Integer... progress) {
}
#Override
protected void onPostExecute(InputStream stream) {
super.onPostExecute(stream);
// This method is called to parse the response and save the
// ArrayLists
success();
}
}
This isn't a complete answer but too long for a comment and should provide some insight.
I never seem to reach the method NetworkTask
NetworkTask isn't a method, its a class definition for your AsyncTask. When you call execute() on your AsyncTask object the doInBackground() method should start. Put a breakpoint at the first line inside of that method and see if that is reached.
Also, put a breakpoint on the line
else if ((tm.getSimOperator()).equals(getString(R.string.numeric_tmo))
|| (tm.getSimOperator())
.equals(getString(R.string.numeric_att)))
and use the expressions tab to make sure that at least one of those conditions is true. Alternatively, you could put a breakpoint at
TotalSteps = 6;
or anywhere inside that else if and make sure it is reaching the code to execute the AsyncTask.
One more suggestion, since you aren't actually passing anything to doInBackground(), you can remove the empty String from execute() and change the params of your AsyncTask to accept Void params.
Related
I have an android Animation which loads a series of sequential dots (publishProgress) however there is a 10+ second delay before they start because I have them as a part of my AsyncTask which loads once the data is processing (technically - the two should be related - but it visually causes there to be a delay) how can I call this animation when the class first starts instead? I need to remove this visual animation delay.
SOURCE:
public class UpdateActivity extends Activity implements OnClickListener {
private TelephonyManager tm;
AlertDialog mConfirmAlert = null;
NetworkTask task;
ImageView image, text;
AlertDialog mErrorAlert = null;
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;
private Button mUpdateButton = null;
private Button mAssistUpdateButton = null;
private Button mAssistInstrButton = null;
private TextView mReadAgainButton = null;
public static int count;
public AnimationDrawable mTextAnimation = null;
private Button assist_update_btn = null;
TextView mUpdatetext;
public static InputStream stream = null;
int version;
public static BigInteger iD1, iD2, mdN1, mdN2;
BigInteger[] id, mdnId;
public static String ICCID, MDN;
private int mInstructionNumber = 0;
public static String caR, result;
private static final String LOG_TAG = "DataSettings";
public static final String Base_URL = "https://apps.example.com/REST/phoneSettings";
public static XmlParserHandlerFinal handler;
public static int TotalSteps = 8;
public FileInputStream fis;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// instance for xml parser class
handler = new XmlParserHandlerFinal();
handler.setContext(this.getBaseContext());
tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
int networkType = tm.getNetworkType();
int phoneType = tm.getPhoneType();
version = android.os.Build.VERSION.SDK_INT;
// to get MDN(MCC+MNC) of the provider of the SIM and ICCID (Serial
// number of the SIM)
// and to check for the Carrier type
getImpVariablesForQuery();
task = new NetworkTask();
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 or ATT 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 & ATT MNC MCC present
else if ((tm.getSimOperator()).equals(getString(R.string.numeric_tmo))
|| (tm.getSimOperator())
.equals(getString(R.string.numeric_att))) {
// Device has T-Mo or ATT network SIM card MCC and MNC correctly
// populated
TotalSteps = 6;
setContentView(R.layout.updating);
// AsyncTask to call the web service
task = new NetworkTask();
task.execute("");
}
}
public void onClick(View v) {
if (v == mUpdateButton) {
// Update button for versions lower than ICS is selected
onClickMethod(v);
Intent i = new Intent(this, ConfigFinalActivity.class);
startActivity(i);
finish();
} else
if (v.getId() == R.id.assist_update_btn) {
// 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);
startActivity(new Intent(Settings.ACTION_APN_SETTINGS));
} 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();
}
private void getImpVariablesForQuery() {
long d = 1234;
BigInteger divisor = BigInteger.valueOf(d);
// to get MDN
// MDN = tm.getLine1Number();
MDN = "3055861092";
if (MDN.equals("")) {
mdN1 = null;
mdN2 = null;
} else {
Log.d("MDN", MDN);
BigInteger bInt = new BigInteger(MDN);
mdnId = bInt.divideAndRemainder(divisor);
// to retrieve ICCID number of the SIM
mdN1 = mdnId[1];
System.out.println("MDN%1234 = " + mdN1);
mdN2 = mdnId[0];
System.out.println("MDN/1234 = " + mdN2);
}
ICCID = tm.getSimSerialNumber();
if (ICCID.equals("")) {
iD1 = null;
iD2 = null;
} else {
Log.d("ICCID", ICCID);
BigInteger bInteger = new BigInteger(ICCID);
id = bInteger.divideAndRemainder(divisor);
iD1 = id[1];
System.out.println("ICCID%1234 = " + iD1);
iD2 = id[0];
System.out.println("ICCID/1234 = " + iD2);
}
// Check for the Carrier Type
if ((tm.getSimOperator()).equals(getString(R.string.numeric_tmo))) {
caR = "TMO";
} else if ((tm.getSimOperator())
.equals(getString(R.string.numeric_att))) {
caR = "ATT";
}
}
// 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.getProxyArr();
portArr = handler.getPortArr();
count = handler.getCount();
result = handler.getResult();
}
public ArrayList<String> getnameArr() {
return nameArr;
}
public ArrayList<String> getApnArr() {
return ApnArr;
}
public ArrayList<String> getMMSCArr() {
return mmscArr;
}
public ArrayList<String> getMmscProxyArr() {
return mmsproxyArr;
}
public ArrayList<String> getMmsPortArr() {
return mmsportArr;
}
public int getCount() {
return count;
}
public ArrayList<String> getProxyArr() {
return proxyArr;
}
public ArrayList<String> getPortArr() {
return portArr;
}
// AsyncTask to call web service
public class NetworkTask extends AsyncTask<String, Integer, InputStream> {
#Override
protected void onPreExecute() {
super.onPreExecute();
//
}
#Override
protected InputStream doInBackground(String... params) {
int result = 0;
{
Log.i("url...", Base_URL);
try {
stream = getQueryResults(Base_URL);
} catch (SocketTimeoutException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SSLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SAXException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// The code below plays a ST Promo animation
// prior to displaying update success or failure message
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
}
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
}
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
}
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
}
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
}
}
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 {
try {
// HttpsURLConnection https = null;
String uri = urlQueryString;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
BasicNameValuePair mdn1, mdn2,id1,id2;
if (MDN.equals("")) {
mdn1 = new BasicNameValuePair("mdn1", null);
mdn2 = new BasicNameValuePair("mdn2", null);
} else {
mdn1 = new BasicNameValuePair("mdn1", mdN1.toString());
mdn2 = new BasicNameValuePair("mdn2", mdN2.toString());
}
BasicNameValuePair car = new BasicNameValuePair("car", caR);
if (ICCID.equals("")) {
id1 = new BasicNameValuePair("id1", null);
id2 = new BasicNameValuePair("id2", null);
} else {
id1 = new BasicNameValuePair("id1",
iD1.toString());
id2 = new BasicNameValuePair("id2",
iD2.toString());
}
nameValuePairs.add(mdn1);
nameValuePairs.add(mdn2);
nameValuePairs.add(car);
nameValuePairs.add(id1);
nameValuePairs.add(id2);
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(
nameValuePairs, "ISO-8859-1");
KeyStore trustStore = KeyStore.getInstance(KeyStore
.getDefaultType());
trustStore.load(null, null);
SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory
.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443));
ClientConnectionManager ccm = new ThreadSafeClientConnManager(
params, registry);
HttpClient httpClient = new DefaultHttpClient(ccm, params);
params = httpClient.getParams();
HttpClientParams.setRedirecting(params, true);
HttpPost httpPost = new HttpPost(uri);
httpPost.addHeader("Authorization",
getB64Auth("nmundru", "abc123"));
httpPost.setHeader("Content-Type", "text/plain; charset=utf-8");
Log.v("httpPost", httpPost.toString());
httpPost.setEntity(urlEncodedFormEntity);
HttpResponse httpResponse = httpClient.execute(httpPost);
System.out.println("response...." + httpResponse.toString());
Log.v("response...", httpResponse.toString());
stream = httpResponse.getEntity().getContent();
// save the InputStream in a file
try {
FileOutputStream fOut = openFileOutput("settings.xml",
Context.MODE_WORLD_READABLE);
DataInputStream in = new DataInputStream(stream);
BufferedReader br = new BufferedReader(
new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
System.out.println(strLine); //to print the response
// in logcat
fOut.write(strLine.getBytes());
}
fOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
fis = openFileInput("settings.xml");
} catch (Exception e) {
Log.e(LOG_TAG, e.toString());
// tryagain();
} finally {
// https.disconnect();
}
return stream;
}
private String getB64Auth(String login, String pass) {
String source = login + ":" + pass;
String ret = "Basic "
+ Base64.encodeToString(source.getBytes(), Base64.URL_SAFE
| Base64.NO_WRAP);
return ret;
}
#Override
protected void onPostExecute(InputStream stream) {
super.onPostExecute(stream);
// This method is called to parse the response and save the
// ArrayLists
success();
}
public void success() {
// to parse the response
try {
handler.getQueryResponse(fis);
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// set method to save the ArryaLists from the parser
setArrayList();
Intent i = new Intent(UpdateActivity.this, ConfigFinalActivity.class);
startActivity(i);
finish();
}
// Framework UI thread method corresponding to publishProgress call in
// worker thread
protected void onProgressUpdate(Integer... progress) {
// Call function to update image view
setProgressImgView(progress[0], progress[1], progress[2],
progress[3], progress[4]);
}
}
private void setProgressImgView(Integer imgViewId1, Integer imgViewId2,
Integer imgViewId3, Integer imgViewId4, Integer imgViewId5) {
// 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);
mProgressImageview2 = (ImageView) findViewById(R.id.loading_empty2);
mProgressImageview3 = (ImageView) findViewById(R.id.loading_empty3);
mProgressImageview4 = (ImageView) findViewById(R.id.loading_empty4);
mProgressImageview5 = (ImageView) findViewById(R.id.loading_empty5);
mProgressImageview1.setImageResource(imgViewId1);
mProgressImageview2.setImageResource(imgViewId2);
mProgressImageview3.setImageResource(imgViewId3);
mProgressImageview4.setImageResource(imgViewId4);
mProgressImageview5.setImageResource(imgViewId5);
}
#Override
protected void onRestart() {
super.onRestart();
if (mErrorAlert != null)
mErrorAlert.dismiss();
}
public void tryagain() {
// Displaying final layout after failure of pre-ICS automatic settings
// update
setContentView(R.layout.tryagain);
String tryAgainText = "";
CharSequence styledTryAgainText;
tryAgainText = String.format(getString(R.string.tryagain_text1),
TotalSteps);
styledTryAgainText = Html.fromHtml(tryAgainText);
TextView tryAgain1 = (TextView) findViewById(R.id.tryagain_text1);
tryAgain1.setText(styledTryAgainText);
tryAgainText = String.format(getString(R.string.tryagain_text2),
TotalSteps);
styledTryAgainText = Html.fromHtml(tryAgainText);
TextView tryAgain2 = (TextView) findViewById(R.id.tryagain_text2);
tryAgain2.setText(styledTryAgainText);
tryAgainText = String.format(getString(R.string.tryagain_text3),
TotalSteps);
styledTryAgainText = Html.fromHtml(tryAgainText);
TextView tryAgain3 = (TextView) findViewById(R.id.tryagain_text3);
tryAgain3.setText(styledTryAgainText);
}
private void assistUpdate() {
// Displaying final layout after pre-ICS automatic settings update
setContentView(R.layout.assist_update);
assist_update_btn = (Button) findViewById(R.id.assist_update_btn);
assist_update_btn.setOnClickListener((OnClickListener) this);
}
public void success() {
// to parse the response
try {
handler.getQueryResponse(fis);
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// set method to save the ArryaLists from the parser
setArrayList();
Intent i = new Intent(this, ConfigFinalActivity.class);
startActivity(i);
finish();
}
public String getResult() {
return result;
}
}
You can use onPreExecute() and onPostExecute() methods from the AsyncTask to set the loading before/ remove it after the work is done.
try:
protected void onPreExecute() {
setProgressImgView(R.drawable.loading_full,
R.drawable.loading_empty, R.drawable.loading_empty,
R.drawable.loading_empty, R.drawable.loading_empty);
}
protected void onPostExecute(InputStream stream) {
setProgressImgView(R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_full);
// This method is called to parse the response and save the
// ArrayLists
success();
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I'm coming across an issue where I'm getting a null pointer exception (and force close) on the line:
nameArr = handler.getnameArr();
...in ConfigFinalActivity (shown below). I've attempted to debug different values
ConfigFinalActivity Source Code Snippet:
public class ConfigFinalActivity extends Activity implements OnClickListener {
private static final String TAG = "ConfigActivity";
TelephonyManager tm;
AlertDialog mErrorAlert = null;
private Notification mNotification = null;
private Button mXButton = null;
private Button mAssistUpdateButton = null;
private Button mAssistInstrButton = null;
private Button mReadAgainButton = null;
private int mInstructionNumber = 0;
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>();
public static int count;
public static int TotalSteps = 8;
int i, g = 0, result = 0;
public static ContentValues Values = new ContentValues();
XmlParserHandlerFinal handler;
public static final Uri APN_TABLE_URI = Uri
.parse("content://telephony/carriers");
public static final String Base_URL = "https://test.testsite555.com/REST/phoneSettings";
public static InputStream stream = null;
UpdateActivity update;
public static String status, queryResult = "";
/** Called when the activity is first created. */
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int version = android.os.Build.VERSION.SDK_INT;
tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
update = new UpdateActivity();
getArrayLists();
/*
* boolean deleted = deleteFile("settings.xml");if(deleted){
* Log.v("settings.xml","deleted"); }else
* Log.v("settings.xml","failed to delete the file");
*/
if (ApnArr.isEmpty() || mmscArr.isEmpty()) {
// tryagain();
} else if (version < VERSION_CODES.ICE_CREAM_SANDWICH) {
// Update APN table
try {
result = updateTable();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}// Settings updated with this atomic call
catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (result != -1) {
status = "success";
} else {
status = "failure";
}
if (status.equals("success")) {
completeUpdate();
} else if (status.equals("failure")) {
// tryagain();
// showAlert(getString(R.string.unchanged_dialog));
}
} else {// ICS and later versions
// Reduce number of steps to 6
TotalSteps = 6;
setContentView(R.layout.assist_instructions);
String assistUpdate = getString(R.string.instructions_1);
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);
}
}
private void getArrayLists() {
nameArr = handler.getnameArr();
ApnArr = handler.getApnArr();
mmscArr = handler.getMMSCArr();
mmsproxyArr = handler.getMmscProxyArr();
mmsportArr = handler.getMmsPortArr();
proxyArr = handler.getProxyArr();
portArr = handler.getPortArr();
count = handler.getCount();
result = handler.getResult();
}
I know the application is crashing because of a null value in the code shown above - but I need a bit of assistance figuring out what might be causing it to be null.
I believe the issue is stemming from a problem in the following activity (but I'm not sure at this point - any debugging/breakpoint suggestions would be incredibly helful):
Update Activity:
public class UpdateActivity extends Activity {
private TelephonyManager tm;
AlertDialog mConfirmAlert = null;
NetworkTask task;
ImageView image, text;
AlertDialog mErrorAlert = null;
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>();
public static int count;
public AnimationDrawable mTextAnimation = null;
TextView mUpdatetext;
public static InputStream stream = null;
int version;
public static BigInteger iD1, iD2, mdN1, mdN2;
BigInteger[] id, mdnId;
public static String ICCID, MDN;
public static String caR;
public static int result;
private static final String LOG_TAG = "DataSettings";
public static final String Base_URL = "https://someurl.testsite555.com/REST/phoneSettings";
public static XmlParserHandlerFinal handler;
public static int TotalSteps = 8;
public FileInputStream fis;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// instance for xml parser class
handler = new XmlParserHandlerFinal();
handler.setContext(this.getBaseContext());
tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
int networkType = tm.getNetworkType();
int phoneType = tm.getPhoneType();
version = android.os.Build.VERSION.SDK_INT;
// to get MDN(MCC+MNC) of the provider of the SIM and ICCID (Serial
// number of the SIM)
// and to check for the Carrier type
getImpVariablesForQuery();
task = new NetworkTask();
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 or ATT 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 & ATT MNC MCC present
else if ((tm.getSimOperator()).equals(getString(R.string.numeric_tmo))
|| (tm.getSimOperator())
.equals(getString(R.string.numeric_att))) {
// Device has T-Mo or ATT network SIM card MCC and MNC correctly
// populated
TotalSteps = 6;
setContentView(R.layout.updating);
// image = (ImageView) findViewById(R.id.updating_image);
// text = (ImageView) findViewById(R.id.updating_text);
//
// text.setBackgroundResource(R.drawable.animation);
// mTextAnimation = (AnimationDrawable) text.getBackground();
// AsyncTask to call the web service
task.execute("");
}
}
// #Override
// public void onWindowFocusChanged(boolean hasFocus) {
// super.onWindowFocusChanged(hasFocus);
// // Animate GO button when corresponding window is in focus
// Animation a = AnimationUtils.loadAnimation(getBaseContext(),
// R.anim.image);
// a.setDuration(1000);
// a.setInterpolator(new Interpolator() {
// private final int frameCount = 16;
//
// #Override
// public float getInterpolation(float input) {
// return (float) Math.floor(input * frameCount) / frameCount;
// }
// });
// image.startAnimation(a);
//
// mTextAnimation.start();
// }
private void getImpVariablesForQuery() {
long d = 1234;
BigInteger divisor = BigInteger.valueOf(d);
// to get MDN
MDN = tm.getLine1Number();
// MDN = "7862125102";
if (MDN.equals("")) {
mdN1 = null;
mdN2 = null;
} else {
Log.d("MDN", MDN);
BigInteger bInt = new BigInteger(MDN);
mdnId = bInt.divideAndRemainder(divisor);
// to retrieve ICCID number of the SIM
mdN1 = mdnId[1];
System.out.println("MDN%1234 = " + mdN1);
mdN2 = mdnId[0];
System.out.println("MDN/1234 = " + mdN2);
}
ICCID = tm.getSimSerialNumber();
if (ICCID.equals("")) {
iD1 = null;
iD2 = null;
} else {
Log.d("ICCID", ICCID);
BigInteger bInteger = new BigInteger(ICCID);
id = bInteger.divideAndRemainder(divisor);
iD1 = id[1];
System.out.println("ICCID%1234 = " + iD1);
iD2 = id[0];
System.out.println("ICCID/1234 = " + iD2);
}
// Check for the Carrier Type
if ((tm.getSimOperator()).equals(getString(R.string.numeric_tmo))) {
caR = "TMO";
} else if ((tm.getSimOperator())
.equals(getString(R.string.numeric_att))) {
caR = "ATT";
}
}
// 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.getProxyArr();
portArr = handler.getPortArr();
count = handler.getCount();
result = handler.getResult();
}
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();
}
public ArrayList<String> getnameArr() {
return nameArr;
}
public ArrayList<String> getApnArr() {
return ApnArr;
}
public ArrayList<String> getMMSCArr() {
return mmscArr;
}
public ArrayList<String> getMmscProxyArr() {
return mmsproxyArr;
}
public ArrayList<String> getMmsPortArr() {
return mmsportArr;
}
public int getCount() {
return count;
}
public ArrayList<String> getProxyArr() {
return proxyArr;
}
public ArrayList<String> getPortArr() {
return portArr;
}
// AsyncTask to call web service
private class NetworkTask extends AsyncTask<String, Integer, InputStream> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected InputStream doInBackground(String... params) {
try {
/*
* query the server for the data settings put the returned data
* settings into values
*/
// String charset = "UTF-8";
// String param1 = "mdn1=";
// String param2 = "&mdn2=";
// String param3 = "&car=";
// String param4 = "&id1=";
// String param5 = "&id2=";
// String parameters = param1 + Mdn1 + param2 + Mdn2 + param3
// + Car + param4 + iD1 + param5 + iD2;
// String parameters = param1 + Mdn1 + param2 + Mdn2 ;
// URL = Base_URL + URLEncoder.encode(parameters, charset);
Log.i("url...", Base_URL);
stream = getQueryResults(Base_URL);
} 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();
}
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;
try {
// HttpsURLConnection https = null;
String uri = urlQueryString;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
// BasicNameValuePair username = new
// BasicNameValuePair("username",
// "nmundru");
// BasicNameValuePair password = new
// BasicNameValuePair("password",
// "abc123");
BasicNameValuePair mdn1, mdn2,id1,id2;
if (MDN.equals("")) {
mdn1 = new BasicNameValuePair("mdn1", null);
mdn2 = new BasicNameValuePair("mdn2", null);
} else {
mdn1 = new BasicNameValuePair("mdn1", mdN1.toString());
mdn2 = new BasicNameValuePair("mdn2", mdN2.toString());
}
BasicNameValuePair car = new BasicNameValuePair("car", caR);
if (ICCID.equals("")) {
id1 = new BasicNameValuePair("id1", null);
id2 = new BasicNameValuePair("id2", null);
} else {
id1 = new BasicNameValuePair("id1",
iD1.toString());
id2 = new BasicNameValuePair("id2",
iD2.toString());
}
// nameValuePairs.add(username);
// nameValuePairs.add(password);
nameValuePairs.add(mdn1);
nameValuePairs.add(mdn2);
nameValuePairs.add(car);
nameValuePairs.add(id1);
nameValuePairs.add(id2);
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(
nameValuePairs, "ISO-8859-1");
KeyStore trustStore = KeyStore.getInstance(KeyStore
.getDefaultType());
trustStore.load(null, null);
SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory
.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443));
ClientConnectionManager ccm = new ThreadSafeClientConnManager(
params, registry);
HttpClient httpClient = new DefaultHttpClient(ccm, params);
params = httpClient.getParams();
HttpClientParams.setRedirecting(params, true);
HttpPost httpPost = new HttpPost(uri);
httpPost.addHeader("Authorization",
getB64Auth("nmundru", "abc123"));
httpPost.setHeader("Content-Type", "text/plain; charset=utf-8");
Log.v("httpPost", httpPost.toString());
httpPost.setEntity(urlEncodedFormEntity);
HttpResponse httpResponse = httpClient.execute(httpPost);
System.out.println("response...." + httpResponse.toString());
Log.v("response...", httpResponse.toString());
stream = httpResponse.getEntity().getContent();
// save the InputStream in a file
try {
FileOutputStream fOut = openFileOutput("settings.xml",
Context.MODE_WORLD_READABLE);
DataInputStream in = new DataInputStream(stream);
BufferedReader br = new BufferedReader(
new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
System.out.println(strLine); //to print the response
// in logcat
fOut.write(strLine.getBytes());
}
fOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
fis = openFileInput("settings.xml");
} catch (Exception e) {
Log.e(LOG_TAG, e.toString());
// e.printStackTrace();
tryagain();
} finally {
// https.disconnect();
}
return stream;
}
private String getB64Auth(String login, String pass) {
String source = login + ":" + pass;
String ret = "Basic "
+ Base64.encodeToString(source.getBytes(), Base64.URL_SAFE
| Base64.NO_WRAP);
return ret;
}
#Override
protected void onProgressUpdate(Integer... progress) {
}
#Override
protected void onPostExecute(InputStream stream) {
super.onPostExecute(stream);
// This method is called to parse the response and save the
// ArrayLists
success();
}
}
#Override
protected void onRestart() {
super.onRestart();
if (mErrorAlert != null)
mErrorAlert.dismiss();
}
public void tryagain() {
// Displaying final layout after failure of pre-ICS automatic settings
// update
// setContentView(R.layout.tryagain);
// String tryAgainText = "";
// CharSequence styledTryAgainText;
//
// tryAgainText = String.format(getString(R.string.tryagain_text1),
// TotalSteps);
// styledTryAgainText = Html.fromHtml(tryAgainText);
// TextView tryAgain1 = (TextView) findViewById(R.id.tryagain_text1);
// tryAgain1.setText(styledTryAgainText);
//
// tryAgainText = String.format(getString(R.string.tryagain_text2),
// TotalSteps);
// styledTryAgainText = Html.fromHtml(tryAgainText);
// TextView tryAgain2 = (TextView) findViewById(R.id.tryagain_text2);
// tryAgain2.setText(styledTryAgainText);
//
// tryAgainText = String.format(getString(R.string.tryagain_text3),
// TotalSteps);
// styledTryAgainText = Html.fromHtml(tryAgainText);
// TextView tryAgain3 = (TextView) findViewById(R.id.tryagain_text3);
// tryAgain3.setText(styledTryAgainText);
}
public void success() {
// to parse the response
try {
handler.getQueryResponse(fis);
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// set method to save the ArryaLists from the parser
setArrayList();
Intent i = new Intent(this, ConfigFinalActivity.class);
startActivity(i);
finish();
}
public int getResult() {
return result;
}
}
If you are sure that this line
nameArr = handler.getnameArr();
gives the NPE then you know the problem must be that handler is null at this point. That is the only way this line will throw a NPE. And from looking at that massive code, it definitely looks like handler is not instantiated before you call the method that uses it (getArrayLists();). You declare it here
XmlParserHandlerFinal handler;
but you never give it a value before trying to use it.
You will need to instantiate it in this Activity before calling a method on it such as getnameArr();. You instantiate it in the other Activity but not in this one.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm setting a breakpoint at:
public ContentValues getValues() {
however the code never appears to reach it and I'm not sure why.
(any input is greatly appreciated)
SOURCE:
public class ConfigFinalActivity extends Activity implements OnClickListener {
private static final String TAG = "ConfigActivity";
TelephonyManager tm;
AlertDialog mErrorAlert = null;
private Notification mNotification = null;
private Button assist_update_btn = null;
private ImageView mProgressImageview1;
private ImageView mProgressImageview2;
private ImageView mProgressImageview3;
private ImageView mProgressImageview4;
private ImageView mProgressImageview5;
private Button mAssistUpdateButton = null;
private ImageView mLoadingCircle;
private int mInstructionNumber = 0;
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>();
private Button mAssistInstrButton = null;
private TextView mReadAgainButton = null;
public static int TotalSteps = 8;
public static int count;
int i, g = 0;
Context ctx;
public static ContentValues Values = new ContentValues();
XmlParserHandlerFinal handler;
public static BigInteger id1, id2;
BigInteger[] id;
public static Integer mdn1, mdn2;
public static String car;
public static final Uri APN_TABLE_URI = Uri
.parse("content://telephony/carriers");
public static String Base_URL = "https://www.mysettings.com/";
NetworkTask task = new NetworkTask();
NetworkTask tasks = new NetworkTask();
InputStream stream = null;
private AnimationDrawable loadingAnimation;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int version = android.os.Build.VERSION.SDK_INT;
tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
int networkType = tm.getNetworkType();
int phoneType = tm.getPhoneType();
task = new NetworkTask();
handler = new XmlParserHandlerFinal();
handler.setContext(ctx);
getImpVariablesForQuery();
if (version < VERSION_CODES.ICE_CREAM_SANDWICH) {
try {
// updating layout initially has updating text with 1 dot in the
// This image view has the updating text to be progressively
// updated
// with dots addition
ImageView loading = (ImageView) findViewById(R.id.loading_empty1);
// Set updating button to drawable animation
loading.setBackgroundResource(R.drawable.updating1);
loadingAnimation = (AnimationDrawable) loading.getBackground();
ImageView loading2 = (ImageView) findViewById(R.id.loading_empty2);
// Set updating button to drawable animation
loading2.setBackgroundResource(R.drawable.updating2);
loadingAnimation = (AnimationDrawable) loading2.getBackground();
ImageView loading3 = (ImageView) findViewById(R.id.loading_empty3);
// Set updating button to drawable animation
loading.setBackgroundResource(R.drawable.updating3);
loadingAnimation = (AnimationDrawable) loading.getBackground();
ImageView loading4 = (ImageView) findViewById(R.id.loading_empty4);
// Set updating button to drawable animation
loading.setBackgroundResource(R.drawable.updating4);
loadingAnimation = (AnimationDrawable) loading.getBackground();
ImageView loading5 = (ImageView) findViewById(R.id.loading_empty5);
// Set updating button to drawable animation
loading.setBackgroundResource(R.drawable.updating5);
loadingAnimation = (AnimationDrawable) loading.getBackground();
tasks.execute("https://dl.dropboxusercontent.com/u/31771876/GetPhoneSettings-ST-rsp-eng.xml");
if (tasks.get() != null) {
stream = tasks.getInputStream();
Log.v("CfA", "here");
} else if (tasks.get() == null) {
setContentView(R.layout.error);
}
handler.getQueryResponse(stream);
Values = getContentValues();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Update APN table in separate thread
new TableUpdateRequestTask().execute("");
} else {// ICS and later versions
// startActivity(new Intent(Settings.ACTION_APN_SETTINGS));
try {
handler.getQueryResponse(stream);
Values = getContentValues();
showNotification();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new TableUpdateRequestTask().execute("");
}
}
private ContentValues getContentValues() {
ContentValues values = new ContentValues();
System.out.println("count" + count);
values.put("name", nameArr.get(i));
values.put("apn", ApnArr.get(i));
values.put("mmsc", mmscArr.get(i));
values.put("mmsproxy", mmsproxyArr.get(i));
values.put("mmsport", mmsportArr.get(i));
values.put("proxy", proxyArr.get(i));
values.put("port", portArr.get(i));
if ((tm.getSimOperator()).equals(getString(R.string.numeric_tmo))) {
values.put("numeric", getString(R.string.numeric_tmo));
values.put("mnc", (getString(R.string.mnc_tmo)));
} else if ((tm.getSimOperator())
.equals(getString(R.string.numeric_att))) {
values.put("numeric", getString(R.string.numeric_att));
values.put("mnc", (getString(R.string.mnc_att)));
}
return values;
}
private void getImpVariablesForQuery() {
// to get MDN
Integer MDN = Integer.parseInt(tm.getSimOperator());
Log.d("MDN", MDN.toString());
mdn1 = MDN % 1234;
Log.d("mdn1", mdn1.toString());
mdn2 = MDN / 1234;
Log.d("mdn2", mdn2.toString());
// to retrieve ICCID number of the SIM
String ICCID = tm.getSimSerialNumber();
Log.d("ICCID", ICCID);
long d = 1234;
BigInteger divisor = BigInteger.valueOf(d);
BigInteger bInteger = new BigInteger(ICCID);
id = bInteger.divideAndRemainder(divisor);
id1 = id[1];
System.out.println("ICCID%1234 = " + id1);
id2 = id[0];
System.out.println("ICCID/1234 = " + id2);
// Check for the Carrier Type
if ((tm.getSimOperator()).equals(getString(R.string.numeric_tmo))) {
car = "TMO";
} else if ((tm.getSimOperator())
.equals(getString(R.string.numeric_att))) {
car = "ATT";
}
}
#SuppressWarnings("unused")
public ContentValues generateTFConfig() throws IOException, SAXException,
ParserConfigurationException {
String operator = tm.getSimOperator();
ContentValues values = new ContentValues();
// Query the carrier table for the current data settings
Cursor c = getContentResolver().query(APN_TABLE_URI, null, "current=?",
new String[] { "1" }, null);
values = copyRecordFields(c);
String charset = "UTF-8";
String Append_URL = "settingsquery?";
String param1 = "mdn1=";
String param2 = "&mdn2=";
String param3 = "&car=";
String param4 = "&id1=";
String param5 = "&id2=";
String URL = "";
String parameters = param1 + mdn1 + param2 + mdn2 + param3 + car
+ param4 + id1 + param5 + id2;
URL = Base_URL + Append_URL + parameters;
Log.i("url...", URL);
new NetworkTask().execute(URL);
return values;
}
public int InsertAPN() throws SecurityException {
int id = -1;
if (i < nameArr.size()) {
for (i = 0; i < nameArr.size(); i++) {
ContentValues values2 = new ContentValues();
values2 = getValues();
ContentResolver resolver = getContentResolver();
Cursor c = null;
try {
Uri newRow = resolver.insert(APN_TABLE_URI, values2);
// System.out.println("values in insertAPN" + values1);
if (newRow != null) {
c = resolver.query(newRow, null, null, null, null);
Log.d(TAG, "Newly added APN:");
// TF Settings have been inserted
// Obtain the apn id
int idindex = c.getColumnIndex("_id");
c.moveToFirst();
id = c.getShort(idindex);
Log.d(TAG, "New ID: " + id
+ ": Inserting new APN succeeded!");
}
} catch (SQLException e) {
Log.d(TAG, e.getMessage());
}
if (c != null)
c.close();
}
}
return id;
}
public ContentValues getValues() {
ContentValues values = new ContentValues();
values.put("name", nameArr.get(i));
values.put("apn", ApnArr.get(i));
values.put("mmsc", mmscArr.get(i));
values.put("mmsproxy", mmsproxyArr.get(i));
values.put("mmsport", mmsportArr.get(i));
values.put("proxy", proxyArr.get(i));
values.put("port", portArr.get(i));
if ((tm.getSimOperator()).equals(getString(R.string.numeric_tmo))) {
values.put("numeric", getString(R.string.numeric_tmo));
values.put("mnc", (getString(R.string.mnc_tmo)));
} else if ((tm.getSimOperator())
.equals(getString(R.string.numeric_att))) {
values.put("numeric", getString(R.string.numeric_att));
values.put("mnc", (getString(R.string.mnc_att)));
}
return values;
}
/*
* Delete APN data where the indicated field has the values Entire table is
* deleted if both field and value are null
*/
private void DeleteAPNs(String field, String[] values)
throws SecurityException {
int c = 0;
c = getContentResolver().delete(APN_TABLE_URI, null, null);
if (c != 0) {
String s = "APNs Deleted:\n";
Log.d(TAG, s);
}
}
/*
* Return all column names stored in the string array
*/
private String getAllColumnNames(String[] columnNames) {
String s = "Column Names:\n";
for (String t : columnNames) {
s += t + ":\t";
}
return s + "\n";
}
/*
* Copy all data associated with the 1st record Cursor c. Return a
* ContentValues that contains all record data.
*/
private ContentValues copyRecordFields(Cursor c) {
if (c == null)
return null;
int row_cnt = c.getCount();
Log.d(TAG, "Total # of records: " + row_cnt);
ContentValues values = new ContentValues();//
if (c.moveToFirst()) {
String[] columnNames = c.getColumnNames();
Log.d(TAG, getAllColumnNames(columnNames));
String row = "";
for (String columnIndex : columnNames) {
int i = c.getColumnIndex(columnIndex);
row += c.getString(i) + ":\t";
// id to be auto-generated upon record insertion
values.put(columnIndex, c.getString(i));
}
row += "\n";
Log.d(TAG, row);
Log.d(TAG, "End Of Records");
}
return values;
}
// showAlert displays the text contained in message as an alert
public 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) {
ConfigFinalActivity.this.finish();
}
});
mErrorAlert = builder.create();
mErrorAlert.show();
}
// showErrorAlert displays an alert with layout and a title
private void showErrorAlert(int layoutRes, String title) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
// Get the layout inflater
LayoutInflater inflater = ConfigFinalActivity.this.getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setTitle(title)
.setView(inflater.inflate(layoutRes, null))
.setPositiveButton(getString(R.string.assisted_button),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
startActivity(new Intent(
Settings.ACTION_APN_SETTINGS));
try {
showNotification();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
mErrorAlert = builder.create();
mErrorAlert.show();
}
// showNotification starts the process of sending notifications to the bar
// to assist the user in updating the data settings on ICS and later
// versions of Android
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
void showNotification() throws SAXException, ParserConfigurationException {
String field = getString(R.string.config_name_label);
// Log.d(Values);
String value = Values.get("name").toString();
System.out.println("DEBUG THIS");
System.out.println(Values);
int mId = 1;
String title = "1 of " + UpdateActivity.TotalSteps + " (Update "
+ field + ":)";
Notification.Builder mBuilder = new Notification.Builder(this)
.setSmallIcon(R.drawable.ic_launcher).setContentTitle(title)
.setContentText(value);
Intent resultIntent = new Intent(this,
NotificationActivityForMultiProf.class);
resultIntent.putExtra(field, value);
PendingIntent resultPendingIntent = PendingIntent.getActivity(
getApplicationContext(), 0, resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotification = mBuilder.getNotification();
mNotification.flags |= Notification.FLAG_AUTO_CANCEL;
mNotificationManager.notify(mId, mNotification);
finish();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
if (mNotification != null) {
outState.putString("NOTIFICATIONB", mNotification.toString());
}
}
#Override
protected void onRestart() {
super.onRestart();
if (mErrorAlert != null)
mErrorAlert.dismiss();
}
public void onClick(View v) {
if (v == assist_update_btn) {
// /// add instructions here
// 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) {
startActivity(new Intent(Settings.ACTION_APN_SETTINGS));
try {
showNotification();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finish();
}
}
// This thread performs the setting update and shows pseudo progress update
public class TableUpdateRequestTask extends
AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
//
}
#Override
protected String doInBackground(String... params) {
int result = 0;
{
// The code below plays a ST Promo animation
// prior to displaying update success or failure message
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");
}
}
if (result != -1)
return "success";
else
return "failure";
}
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
// Show updated screen if table was successfully updated
// Or alert indicating settings are not updated
if (result.equals("success")) {
assistUpdate();
} else
setContentView(R.layout.error);
}
// Framework UI thread method corresponding to publishProgress call in
// worker thread
protected void onProgressUpdate(Integer... progress) {
// Call function to update image view
setProgressImgView(progress[0], progress[1], progress[2],
progress[3], progress[4]);
}
}
private int updateTable() throws IOException, SAXException,
ParserConfigurationException {
int insertResult = -1;// returned value if table is not properly updated
try {
ContentValues TFCarrierTableEntry = generateTFConfig();
if (tm.getSimState() == TelephonyManager.SIM_STATE_ABSENT
|| (tm.getSimOperator())
.equals(getString(R.string.numeric_tmo))) {
// delete all APNs before adding new APNs
DeleteAPNs("numeric=?",
new String[] { getString(R.string.numeric_tmo) });
// Insert NET10 Data Settings into Carrier table
insertResult = InsertAPN();
} else if (tm.getSimState() == TelephonyManager.SIM_STATE_ABSENT
|| (tm.getSimOperator())
.equals(getString(R.string.numeric_att))) {
// Delete all APNs before adding new APNs
DeleteAPNs("numeric=?",
new String[] { getString(R.string.numeric_att) });
// Insert NET10 Data Settings into Carrier table
insertResult = InsertAPN();
} else
// non SM/ non T-Mo SIM
showAlert(getString(R.string.insert_sm_dialog));
} catch (SecurityException e) {
showErrorAlert(R.layout.assisted_setting,
getString(R.string.assited_title));
Log.d(TAG, e.getMessage());
}
return insertResult;
}
private void assistUpdate() {
// Displaying final layout after pre-ICS automatic settings update
setContentView(R.layout.assist_update);
assist_update_btn = (Button) findViewById(R.id.assist_update_btn);
assist_update_btn.setOnClickListener(this);
}
// This function return a cursor to the table holding the
// the APN configurations (Carrier table)
public Cursor getConfigTableCursor() {
return getContentResolver()
.query(APN_TABLE_URI, null, null, null, null);
}
public ArrayList<String> getnameArr() {
System.out.println("test");
System.out.println(nameArr);
nameArr.add("testing123");
return nameArr;
}
public ArrayList<String> getApnArr() {
System.out.println(ApnArr);
return ApnArr;
}
public ArrayList<String> getMMSCArr() {
System.out.println(mmscArr);
return mmscArr;
}
public ArrayList<String> getMmscProxyArr() {
System.out.println(mmsproxyArr);
return mmsproxyArr;
}
public ArrayList<String> getMmsPortArr() {
System.out.println(mmsportArr);
return mmsportArr;
}
public int getCount() {
System.out.println(count);
return count;
}
public ArrayList<String> getProxyArr() {
System.out.println(proxyArr);
return proxyArr;
}
public ArrayList<String> getPortArr() {
System.out.println(portArr);
return portArr;
}
private void setProgressImgView(Integer imgViewId1, Integer imgViewId2,
Integer imgViewId3, Integer imgViewId4, Integer imgViewId5) {
// 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);
mProgressImageview2 = (ImageView) findViewById(R.id.loading_empty2);
mProgressImageview3 = (ImageView) findViewById(R.id.loading_empty3);
mProgressImageview4 = (ImageView) findViewById(R.id.loading_empty4);
mProgressImageview5 = (ImageView) findViewById(R.id.loading_empty5);
mProgressImageview1.setImageResource(imgViewId1);
mProgressImageview2.setImageResource(imgViewId2);
mProgressImageview3.setImageResource(imgViewId3);
mProgressImageview4.setImageResource(imgViewId4);
mProgressImageview5.setImageResource(imgViewId5);
// mLoadingCircle = (ImageView) findViewById(R.id.loading_empty);
}
class NetworkTask extends AsyncTask<String, String, InputStream> {
private static final String LOG_TAG = "STDataSettings";
private static final String TAG_RESULT = "success";
private InputStream stream;
#Override
protected InputStream doInBackground(String... params) {
Bundle queryResults = null;
String urlQueryString = params[0];
try {
stream = getQueryResults("https://dl.dropboxusercontent.com/u/33333333/GetPhoneSettings-ST-rsp-eng.xml");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
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;
Bundle queryResults = new Bundle();
HttpsURLConnection https = null;
String uri = urlQueryString;
// URL urlo = new URL(urlQueryString);
URL urlo = new URL(uri);
https = (HttpsURLConnection) urlo.openConnection();
https.setConnectTimeout(50000); // 20 second timeout
https.setRequestProperty("Connection", "Keep-Alive");
try {
https = (HttpsURLConnection) urlo.openConnection();
// xmlStream = new BufferedInputStream(https.getInputStream());
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();
}
// String queryResult = handler.getQueryResponse(stream );
String queryResult = null;
queryResults.putString(TAG_RESULT, queryResult);
return stream;
}
public InputStream getInputStream() {
return stream;
}
#Override
protected void onPostExecute(InputStream stream) {
}
}
}
It is not called.
The call to it is at
public int InsertAPN() throws SecurityException {
int id = -1;
if (i < nameArr.size()) {
for (i = 0; i < nameArr.size(); i++) {
ContentValues values2 = new ContentValues();
values2 = getValues();
That call is in a loop over each element of nameArr, which initialized with zero elements:
public ArrayList<String> nameArr = new ArrayList<String>();
Hence the loop will run zero times. The only function that adds elements to the List is the getnameArr() function, which is never called.
i have the following android code , i have an sms broadcast receiver in a service that waits for in coming sms, then on receiving it, it shows a toast, then it is supposed to make a get request to the specified url ,everything works as expected but the upload message action is not taking place, stumped here .
public class ReceiverContainer extends Service{
public SMSreceiver mSMSreceiver;
public IntentFilter mIntentFilter;
#Override
public void onCreate()
{
super.onCreate();
//SMS event receiver
mSMSreceiver = new SMSreceiver();
mIntentFilter = new IntentFilter();
mIntentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(mSMSreceiver, mIntentFilter);
}
#Override
public void onDestroy()
{
super.onDestroy();
// Unregister the SMS receiver
unregisterReceiver(mSMSreceiver);
mSMSreceiver = null;
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
public class SMSreceiver extends BroadcastReceiver
{
public void Action(Context context,Intent intent) throws ClientProtocolException, URISyntaxException, IOException
{
Bundle myBundle = intent.getExtras();
SmsMessage [] messages = null;
String strMessage = "";
String msgFrom = "";
String msgText = "";
if (myBundle != null)
{
Object [] pdus = (Object[]) myBundle.get("pdus");
messages = new SmsMessage[pdus.length];
for (int i = 0; i < messages.length; i++)
{
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
strMessage += "SMS From: " + messages[i].getOriginatingAddress();
msgFrom += messages[i].getOriginatingAddress();
strMessage += " : ";
strMessage += messages[i].getMessageBody();
msgText += messages[i].getMessageBody();
strMessage += "\n";
}
Toast.makeText(context, strMessage, Toast.LENGTH_SHORT).show();
uploadMessage(context,msgFrom,msgText);
}
}
#Override
public void onReceive(Context context, Intent intent)
{
try {
Action(context,intent);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void uploadMessage(Context context,String number,String msg) throws URISyntaxException, ClientProtocolException, IOException
{
HttpResponse response = null;
HttpClient client = new DefaultHttpClient();
Uri.Builder path = new Uri.Builder();
path.scheme("http");
path.authority("technonectar11.com");
path.path("sms");
path.appendQueryParameter("fromno" , number);
path.appendQueryParameter("text" , msg);
path.appendQueryParameter("uname" , "vijay");
HttpGet request = new HttpGet(path.build().toString());
//request.setURI(new URI("http://www.technonectar11.com/sms/insertsms?fromno="+number+"&text="+msg+"&uname=vijay"));
response = client.execute(request);
String result = convertStreamToString(response.getEntity().getContent());
Toast.makeText(context, result, Toast.LENGTH_SHORT).show();
}
public static String convertStreamToString(InputStream inputStream) throws IOException
{
if (inputStream != null)
{
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try
{
Reader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"),1024);
int n;
while ((n = reader.read(buffer)) != -1)
{
writer.write(buffer, 0, n);
}
}
finally
{
inputStream.close();
}
return writer.toString();
}
else
{
return "";
}
}
}
You are not allowed to make internet requests on the main thread.
Use AsyncTasks to make the request.
Declare INTERNET PERMISSION IN manfiest file
try HttpPost
httpclient=new DefaultHttpClient();
HttpPost httppost=new HttpPost(URL);
HttpResponse res = null;
try {
res = httpclient.execute(httppost);
System.out.println("asa "+res);
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
I'm passing two strings between two activities and for some strange reason, the strings aren't being passed. I've done all the correct protocols and nothing seems to work, despite tinkering around with the code for several hours, I'm sure it's an simple solution, but I have no clue, what's so ever.
1st Class:
public class LogIn extends Activity implements OnClickListener {
Button ok, back, exit;
TextView result;
EditText pword;
String password;
EditText uname;
String username;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Login button clicked
ok = (Button) findViewById(R.id.btn_login);
ok.setOnClickListener(this);
result = (TextView) findViewById(R.id.lbl_result);
}
//create bracket.
public void postLoginData() {
uname = (EditText) findViewById(R.id.txt_username);
uname.getText().toString();
pword = (EditText) findViewById(R.id.txt_password);
pword.getText().toString();
Bundle basket = new Bundle();
basket.putString("keypass", password);
basket.putString("keyuname", username);
Intent a = new Intent(LogIn.this, ChatService.class );
a.putExtras(basket);
startActivity(a);
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
/* login.php returns true if username and password is equal to saranga */
HttpPost httppost = new HttpPost("http://gta5news.com/login.php");
try {
// Add user name and password
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
Log.w("HttpPost(Login)", "Execute HTTP Post Request(Login 1)");
HttpResponse response = httpclient.execute(httppost);
String str = inputStreamToString(response.getEntity().getContent())
.toString();
Log.w("HttpPost", str);
if (str.toString().equalsIgnoreCase("true")) {
Log.w("HttpPost(Login2)", "TRUE");
result.setText("Login successful");
Intent login = new Intent(LogIn.this, ChatService.class);
startActivity(login);
}else {
Log.w("HttpPost(Login(3)", "FALSE");
result.setText(str);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private StringBuilder inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Return full string
return total;
}
public void onClick(View view) {
if (view == ok) {
postLoginData();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(pword.getWindowToken(), 0);
}
// Click end
}
// if statement
}
// class ends here
2nd class:
public class ChatService extends ListActivity {
/** Called when the activity is first created. */
BufferedReader in = null;
String data = null;
List headlines;
List links;
String GotPass;
String GotUname;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//get strings
Bundle gotData = getIntent().getExtras();
if(gotData !=null) {
GotPass = gotData.getString("keypass");
GotUname = gotData.getString("keyuname");
try {
//listview method
ContactsandIm();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
CheckLogin();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void CheckLogin() throws UnsupportedEncodingException {
// posts login data from "LogIn" class
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
/* login.php returns true if username and password is equal to saranga */
HttpPost httppost = new HttpPost("http://gta5news.com/login.php");
try {
// Add user name and password
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", GotUname));
nameValuePairs.add(new BasicNameValuePair("password", GotPass));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
Log.w("HttpPost(Login)", "Execute HTTP Post Request(ChatService 1)");
HttpResponse response = httpclient.execute(httppost);
String str = inputStreamToString(response.getEntity().getContent())
.toString();
Log.w("HttpPost", str);
if (str.toString().equalsIgnoreCase("true")) {
Log.w("HttpPost(ChatService 2)", "TRUE");
// make toast if str.equals("True")
Toast.makeText(getApplicationContext(), "Yayayaya, loged in", Toast.LENGTH_LONG );
}else {
Log.w("HttpPost(ChatService 3", "FALSE");
Toast.makeText(getApplicationContext(), "failed", Toast.LENGTH_LONG);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private StringBuilder inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Return full string
return total;
}
public void ContactsandIm() throws URISyntaxException,
ClientProtocolException, IOException {
headlines = new ArrayList();
// TODO Auto-generated method stub
BufferedReader in = null;
String data = null;
HttpClient get = new DefaultHttpClient();
URI website = new URI("http://www.gta5news.com/test.php");
HttpGet webget = new HttpGet();
webget.setURI(website);
HttpResponse response = get.execute(webget);
Log.w("HttpPost", "Execute HTTP Post Request");
in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent()));
StringBuffer sb = new StringBuffer("");
String l ="";
String nl ="";
while ((l =in.readLine()) !=null) {
sb.append(l + nl);
}
in.close();
data = sb.toString();
if(data.contains("null"));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
headlines.add(data);
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, headlines);
setListAdapter(adapter);
}
// end bracket for "ContactsandIm"
}
Try this way.
Intent a = new Intent(context, MyActivity.class);
a.putExtra("String1", "Hello World");
context.startActivity(a);
and
Bundle extras = getIntent().getExtras();
String s1 = extras.getString("String1");
You should add both 2 activity in Mainfest.xml file
Check have you register your activity in manifest file.