我有登录活动,活动在顶部显示新闻更新。为了显示新闻更新,在活动的onCreate方法中,我异步发布到url以获取新闻的XML。一切都运行正常,但有时候,选框会给我一个空指针异常。
活动代码:
public class LoginActivity extends Activity {
Button login;
EditText txtUsername;
EditText txtPassword;
//variables to send post request
String responseBody;
String responseCode;
//Progressbar object
ProgressDialog progress;
//checkbox obj
CheckBox remember_me;
//not a member textview
TextView notMember;
TextView otpRegister;
//String marquee
String marqueeHtml;
//variables to send post request for marquee
String marqueeResponseBody;
String marqueeResponseCode;
String marqueeContent;
String marqueeToDisplay="";
TextView marqueeTextView;
// Exam list XML node keys
static final String KEY_NEWS = "News"; // parent node
static final String KEY_COLOR = "color";
static final String KEY_TEXT = "text";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_LEFT_ICON);
setContentView(R.layout.activity_login);
//setting icon to title bar
getWindow().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON,R.drawable.ic_launcher);
//===============For marquee place holder===================================
marqueeTextView = (TextView) findViewById(R.id.marquee_textView);
marqueeTextView.setText(Html.fromHtml("Welcome"));
marqueeTextView.setSelected(true);
//===============For marquee===================================
isOnline_marquee();
//Putting first part of URL in preferences-------------------------------------------------------------
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
//Hosted url
editor.putString("URLFirstPart","http://203.153.37.13:89/AndroidService.asmx/");
editor.commit();
//-----------------------------------------------------------------------------------------------
txtUsername = (EditText) findViewById(R.id.txtUsername);
txtPassword = (EditText) findViewById(R.id.txtPassword);
remember_me=(CheckBox)findViewById(R.id.remember_me_checkBox);
//getting user id and password from preference
String remember_user= preferences.getString("remember_user","");
String remember_password=preferences.getString("remember_password","");
//setting username and password to text box
txtUsername.setText(remember_user);
txtPassword.setText(remember_password);
// onclick login button
login = (Button) findViewById(R.id.login_button);
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//checking whether there are values in the textboxes
String userId = txtUsername.getText().toString();
String password = txtPassword.getText().toString();
if (userId.trim().length() == 0
|| password.trim().length() == 0) {
create_alert("Warning","Please enter your userID and Password");
}
//if credentials match then forwarding to take a test activity
else
{
if (remember_me.isChecked())
{
saveInPreference("remember_user", txtUsername.getText().toString());
saveInPreference("remember_password", txtPassword.getText().toString());
}
//checking internet connectivity before sending login request
isOnline();
}
}
});
saveInPreference("showTab", "Exam");
// onclick not member textview
notMember = (TextView) findViewById(R.id.not_member_textView);
notMember.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//going to next register activity
Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
finish();
LoginActivity.this.startActivity(intent);
}
});
// onclick not OTP textview
otpRegister = (TextView) findViewById(R.id.otp_reg_textView);
otpRegister.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//going to next otp register activity
Intent intent = new Intent(LoginActivity.this, OtpRegisterActivity.class);
finish();
LoginActivity.this.startActivity(intent);
}
});
}
@Override
public void onBackPressed() {
// do something on back.
twoButtonAlert("Please Note", "Sure you want to quit application?", "Yes", "No");
return;
}
//check connection
public boolean isOnline() {
ConnectivityManager cm =(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
//starting the progress bar
progress = ProgressDialog.show(this, "Please Wait", "Logging in", true);
//sending request for login
new MyAsyncTask().execute(txtUsername.getText().toString(),txtPassword.getText().toString());
return true;
}
//alert box to show internet connection error
AlertDialog.Builder Internet_Alert = new AlertDialog.Builder(LoginActivity.this);
// set title
Internet_Alert.setCancelable(false);
Internet_Alert.setTitle("Attention!");
Internet_Alert.setMessage("This application requires internet connectivity, no internet connection detected");
Internet_Alert.setPositiveButton("Quit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1)
{
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
onQuitPressed();
}
});
Internet_Alert.create().show();
return false;
}
//to remove application from task manager
public void onQuitPressed() {
int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);
}
//to create alert message
public void create_alert(String title, String message)
{
AlertDialog.Builder alertDialog = new AlertDialog.Builder(LoginActivity.this);
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
//method to show toast message
public void makeAToast(String str) {
//yet to implement
Toast toast = Toast.makeText(this,str, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
//===================================================================================================================================
//sending EmailAddress and Password to server
//===================================================================================================================================
private class MyAsyncTask extends AsyncTask<String, Integer, Double>{
@Override
protected Double doInBackground(String... params) {
// TODO Auto-generated method stub
postData(params[0],params[1]);
return null;
}
protected void onPostExecute(Double result){
if(responseBody.contains("TRUE"))
{
String raw=responseBody;
raw = raw.substring(0, raw.lastIndexOf("<"));
raw = raw.substring(raw.lastIndexOf(">") + 1, raw.length());
String [] contents = raw.split(",");
//extracting user name and user id from response
String user_name=contents[1];
String student_code=contents[2];
//save user name and user id in preference
saveInPreference("user_name",user_name);
saveInPreference("student_code",student_code);
//login is successful, going to next activity
Intent intent = new Intent(LoginActivity.this, TakeTestActivity.class);
//hiding progress bar
progress.dismiss();
finish();
LoginActivity.this.startActivity(intent);
}
else
{
//hiding progress bar
progress.dismiss();
create_alert("Attention!", "Please provide valid userid and password");
}
}
protected void onProgressUpdate(Integer... progress){
}
@SuppressWarnings("deprecation")
public void postData(String emailId,String passwrd) {
//to handle connection timeout
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
HttpConnectionParams.setSoTimeout(httpParams, 10000);
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient(httpParams);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(LoginActivity.this);
final String url_first = preferences.getString("URLFirstPart","");
HttpPost httppost = new HttpPost(url_first+"ValidateLogin");
try {
// Data that I am sending
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("EmailId", emailId));
nameValuePairs.add(new BasicNameValuePair("Password", passwrd));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
try
{
// Execute HTTP Post Request
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
//getting response body and code from the server
responseCode=""+ response.getStatusLine().getStatusCode();
responseBody = EntityUtils.toString(response.getEntity());
}
catch (SocketTimeoutException ex)
{
//showing alert in case of connection timeout
AlertDialog alertDialog = new AlertDialog.Builder(LoginActivity.this).create();
// Setting Dialog Title
alertDialog.setTitle("Please Note");
// Setting Dialog Message
alertDialog.setMessage("Connection problem, please try later!");
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog closed
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
Log.d("Login response body: ", responseBody);
Log.d("Login response code: ", responseCode);
}
catch (Throwable t ) {
}
}
}
//===================================================================================================================================
//END sending EmailAddress and Password to server
//===================================================================================================================================
//method to save variable in preference
public void saveInPreference(String name, String content)
{
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(name,content);
editor.commit();
}
//method to show double button alert dialog
public void twoButtonAlert(String title, String message, String button1, String button2)
{
AlertDialog.Builder alertDialog = new AlertDialog.Builder(LoginActivity.this);
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
// Setting Positive "Yes" Button
alertDialog.setPositiveButton(button1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
// Write your code here to invoke YES event
finish();
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton(button2, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to invoke NO event
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
//getting content from preferences
public String getFromPreference(String variable_name)
{
String preference_return;
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
preference_return = preferences.getString(variable_name,"");
return preference_return;
}
//check connection for marquee
public boolean isOnline_marquee() {
ConnectivityManager cm =(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
//sending request for login
new MyAsyncTask_marquee().execute();
return true;
}
//alert box to show internet connection error
AlertDialog.Builder Internet_Alert = new AlertDialog.Builder(LoginActivity.this);
// set title
Internet_Alert.setCancelable(false);
Internet_Alert.setTitle("Attention!");
Internet_Alert.setMessage("This application requires internet connectivity, no internet connection detected");
Internet_Alert.setPositiveButton("Quit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1)
{
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
onQuitPressed();
}
});
Internet_Alert.create().show();
return false;
}
//===================================================================================================================================
//sending request for marquee to server
//===================================================================================================================================
private class MyAsyncTask_marquee extends AsyncTask<String, Integer, Double>{
@Override
protected Double doInBackground(String... params) {
// TODO Auto-generated method stub
postData();
return null;
}
protected void onPostExecute(Double result){
marqueeContent=marqueeResponseBody;
parse_MarqueeContent();
}
protected void onProgressUpdate(Integer... progress){
}
@SuppressWarnings("deprecation")
public void postData() {
//to handle connection timeout
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
HttpConnectionParams.setSoTimeout(httpParams, 10000);
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient(httpParams);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(LoginActivity.this);
final String url_first = preferences.getString("URLFirstPart","");
HttpPost httppost = new HttpPost(url_first+"NewsScroller");
try {
// Data that I am sending
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
try
{
// Execute HTTP Post Request
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
//getting response body and code from the server
marqueeResponseCode=""+ response.getStatusLine().getStatusCode();
marqueeResponseBody = EntityUtils.toString(response.getEntity());
}
catch (SocketTimeoutException ex)
{
//showing alert in case of connection timeout
AlertDialog alertDialog = new AlertDialog.Builder(LoginActivity.this).create();
// Setting Dialog Title
alertDialog.setTitle("Please Note");
// Setting Dialog Message
alertDialog.setMessage("Connection problem, please try later!");
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog closed
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
Log.d("Marquee response body: ", marqueeResponseBody);
Log.d("Marquee response code: ", marqueeResponseCode);
}
catch (Throwable t ) {
}
}
}
//===================================================================================================================================
//END sending request for marquee to server
//===================================================================================================================================
// function to populate marquee from xml
void parse_MarqueeContent()
{
XMLParser parser = new XMLParser();
Document doc = parser.getDomElement(marqueeContent); // getting DOM element
//list object to populate spinner
List<String> list = new ArrayList<String>();
NodeList nl = doc.getElementsByTagName(KEY_NEWS);
// looping through all item nodes <item>
for ( int i = 0; i < nl.getLength();i++) {
// creating new HashMap
Element e = (Element) nl.item(i);
String color=parser.getValue(e, KEY_COLOR);
String text=parser.getValue(e, KEY_TEXT);
marqueeToDisplay=marqueeToDisplay+"<font color="+color+">"+text+"</font>";
}
//===============For marquee===================================
saveInPreference("marquee_Html_content", marqueeToDisplay);
marqueeTextView.setText(Html.fromHtml(marqueeToDisplay));
marqueeTextView.setSelected(true);
//===============For marquee===================================
}
}
活动正常工作时的屏幕截图:
在活动的顶部,会显示选框。
发布请求失败时的logcat报告:
04-26 04:56:11.663: E/AndroidRuntime(909): FATAL EXCEPTION: main
04-26 04:56:11.663: E/AndroidRuntime(909): java.lang.NullPointerException
04-26 04:56:11.663: E/AndroidRuntime(909): at java.io.StringReader.<init>(StringReader.java:47)
04-26 04:56:11.663: E/AndroidRuntime(909): at com.ica.commons.XMLParser.getDomElement(XMLParser.java:72)
04-26 04:56:11.663: E/AndroidRuntime(909): at com.ica.bankpoexamination2.LoginActivity.parse_MarqueeContent(LoginActivity.java:623)
04-26 04:56:11.663: E/AndroidRuntime(909): at com.ica.bankpoexamination2.LoginActivity$MyAsyncTask_marquee.onPostExecute(LoginActivity.java:539)
04-26 04:56:11.663: E/AndroidRuntime(909): at com.ica.bankpoexamination2.LoginActivity$MyAsyncTask_marquee.onPostExecute(LoginActivity.java:1)
04-26 04:56:11.663: E/AndroidRuntime(909): at android.os.AsyncTask.finish(AsyncTask.java:631)
04-26 04:56:11.663: E/AndroidRuntime(909): at android.os.AsyncTask.access$600(AsyncTask.java:177)
04-26 04:56:11.663: E/AndroidRuntime(909): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
04-26 04:56:11.663: E/AndroidRuntime(909): at android.os.Handler.dispatchMessage(Handler.java:99)
04-26 04:56:11.663: E/AndroidRuntime(909): at android.os.Looper.loop(Looper.java:137)
04-26 04:56:11.663: E/AndroidRuntime(909): at android.app.ActivityThread.main(ActivityThread.java:5041)
04-26 04:56:11.663: E/AndroidRuntime(909): at java.lang.reflect.Method.invokeNative(Native Method)
04-26 04:56:11.663: E/AndroidRuntime(909): at java.lang.reflect.Method.invoke(Method.java:511)
04-26 04:56:11.663: E/AndroidRuntime(909): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
04-26 04:56:11.663: E/AndroidRuntime(909): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
04-26 04:56:11.663: E/AndroidRuntime(909): at dalvik.system.NativeStart.main(Native Method)
应该怎样处理这种情况?我不希望应用程序在这种情况下强行关闭。