此代码工作正常但是当我在侧边栏菜单中创建一个注销按钮时,它会停止工作并且应用程序立即崩溃:
package com.example.bulksms;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
@SuppressWarnings("deprecation")
@SuppressLint({ "NewApi", "ShowToast" })
public class MainActivity extends Activity {
EditText Username;
EditText Password;
String line=null;
// ProgressDialog
ProgressDialog progress;
//ProgressDialog progress;
// flag for Internet connection status
Boolean isInternetPresent = false;
//session
SessionManager session;
// Connection detector class
ConnectionDetector cd;
//
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// creating connection detector class instance
cd = new ConnectionDetector(getApplicationContext());
// get Internet status
isInternetPresent = cd.isConnectingToInternet();
//if TheradPolicy When app crash automatically.
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
//Array List For Branch Showing
try {
if (isInternetPresent)
{
// Session manager
session = new SessionManager(getApplicationContext());
if (session.isLoggedIn()) {
// User is already logged in. Take him to main activity
Intent intent = new Intent(MainActivity.this, Home.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
else{
Showing_branch();
}
}
else
{
// Internet connection is not present
// Ask user to connect to Internet
showAlertDialog(MainActivity.this, "No Internet Connection","You don't have internet connection.", false);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("Error In Showing Branch", e.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Get Activity Main Data.
Button submit;
Username = (EditText)findViewById(R.id.username);
Password = (EditText)findViewById(R.id.password);
submit = (Button)findViewById(R.id.submitbtn);
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Spinner Branch_Name = (Spinner)findViewById(R.id.simple_spinner_item);
Toast.makeText(getBaseContext(), "Select value:"+Branch_Name.getSelectedItem().toString(), Toast.LENGTH_LONG).show();
if(Branch_Name.getSelectedItem().toString()=="")
{
TextView tvInvisibleError = (TextView)findViewById(R.id.tvInvisibleError);
tvInvisibleError.setError( "Select Branch name!" );
tvInvisibleError.setTextColor(Color.RED);
}
else if(Username.getText().toString().trim().equals(""))
{
Username.setError( "Username name is required!" );
Username.setTextColor(Color.RED);
Username.setHint("Enter UserName!");
}
else if(Password.getText().toString().trim().equals(""))
{
Password.setError( "Password is required!" );
Password.setTextColor(Color.RED);
Password.setHint( "Enter Password !" );
}
else
{
try {
Login(Username.getText().toString().trim(),Password.getText().toString().trim(),Branch_Name.getSelectedItem().toString());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
}
/**
* Function to Showing Branch List
* using This Function get Branch List form SERVER.
* */
void Showing_branch() throws ClientProtocolException, IOException, JSONException {
//
progress = ProgressDialog.show(this, "Loading",
"Loading..", true);
new Thread(new Runnable() {
@Override
public void run()
{
// do the thing that takes a long time
runOnUiThread(new Runnable() {
@Override
public void run()
{
//progress.dismiss();
}
});
}
}).start();
// TODO Auto-generated method stub
Spinner mSpinner = (Spinner)findViewById(R.id.simple_spinner_item);
ArrayList<String> options=new ArrayList<String>();
options.add("");
//options.add("option 3");
//Get Server Value
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://ayattechnologies.com/demo/sentsms/getNumber.php?Getdata=true");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream InputIs = entity.getContent();
//
BufferedReader reader = new BufferedReader(new InputStreamReader(InputIs,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
InputIs.close();
String result = sb.toString();
//Get The json Data
JSONArray aJson = new JSONArray(result);
for(int i=0; i<aJson.length(); i++)
{
JSONObject branchlist = aJson.getJSONObject(i);
String branch_id = branchlist.getString("phoneNumber");
options.add(branch_id);
}
//
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,options);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
mSpinner.setAdapter(adapter);
progress.dismiss();
}
/**
* Function to Login User
* @param:Username
* @param:Password
* @param:BranchName
* */
public void Login(String Username, String Password,String branchName) throws ClientProtocolException, IOException, JSONException {
// TODO Auto-generated method stub
progress = ProgressDialog.show(this, "Login",
"Loading..", true);
new Thread(new Runnable() {
@Override
public void run()
{
// do the thing that takes a long time
runOnUiThread(new Runnable() {
@Override
public void run()
{
//progress.dismiss();
}
});
}
}).start();
//Toast.makeText(getBaseContext(), "Username:"+Username, Toast.LENGTH_LONG).show();
// Creating HTTP client
HttpClient httpClient = new DefaultHttpClient();
// Creating HTTP Post
HttpPost httpPost = new HttpPost("http://ayattechnologies.com/demo/sentsms/login.php");
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair("username",Username ));
nameValuePair.add(new BasicNameValuePair("password",Password ));
nameValuePair.add(new BasicNameValuePair("branch",branchName ));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpClient.execute(httpPost);
Log.d("Http Response:", response.toString());
HttpEntity entity = response.getEntity();
InputStream Is_response = entity.getContent();
BufferedReader reader = new BufferedReader
(new InputStreamReader(Is_response,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
Is_response.close();
String result = sb.toString();
JSONArray aJson = new JSONArray(result);
String responsedString = null;
for(int i=0; i<aJson.length(); i++)
{
JSONObject json = aJson.getJSONObject(i);
responsedString = json.getString("Success");
}
Log.d("Http Response:", responsedString);
//dismiss progressbar
if(responsedString.equals("Success"))
{
Toast.makeText(getBaseContext(), "responseData:"+responsedString, Toast.LENGTH_LONG).show();
//progress.dismiss();
// Create login session
session = new SessionManager(getApplicationContext());
session.setLogin(true);
session.setusename(Username);
//
Intent i = new Intent(getBaseContext(), Home.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
}
else{
progress.dismiss();
}
//
//Toast.makeText(getBaseContext(), "responseData:"+responsed, Toast.LENGTH_LONG).show();
// Toast.makeText(getBaseContext(), "responseData:"+aJson, Toast.LENGTH_LONG).show();
}
/**
* Function to display simple Alert Dialog
* @param context - application context
* @param title - alert dialog title
* @param message - alert message
* @param status - success/failure (used to set icon)
* */
public void showAlertDialog(Context context, String title, String message, Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
// Setting alert dialog icon
alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
});
// Showing Alert Message
alertDialog.show();
}
}
退出片段代码
如果我把任何其他应用程序崩溃的任何代码按钮
package com.example.bulksms;
import android.annotation.SuppressLint;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
@SuppressLint("NewApi")
public class LogoutFragment extends Fragment {
//session
SessionManager session;
Context _context;
public LogoutFragment(){
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.logout_fragment, container, false);
session.logoutUser();
return rootView;
}
}
此处的会话管理器课程
package com.example.bulksms;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;
public class SessionManager {
// LogCat tag
private static String TAG = SessionManager.class.getSimpleName();
// Shared Preferences
SharedPreferences pref;
Editor editor;
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Shared preferences file name
private static final String PREF_NAME = "BulkSms";
private static final String KEY_IS_LOGGEDIN = "isLoggedIn";
public SessionManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void setLogin(boolean isLoggedIn) {
editor.putBoolean(KEY_IS_LOGGEDIN, isLoggedIn);
// commit changes
editor.commit();
Log.d(TAG, "User login session modified!");
}
public boolean isLoggedIn(){
return pref.getBoolean(KEY_IS_LOGGEDIN, false);
}
//
public void setusename(String usename) {
pref.edit().putString("Username", usename).commit();
editor.commit();
}
//
public String getusename() {
String usename = pref.getString("Username","");
return usename;
}
/**
* Clear session details
* */
public void logoutUser(){
// Clearing all data from Shared Preferences
editor.clear();
editor.commit();
_context.getSharedPreferences("BulkSms", 0).edit().clear().commit();
// After logout redirect user to Loing Activity
Intent i = new Intent(_context, MainActivity.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
}
}
错误LogCat
12-31 10:40:23.830: E/AndroidRuntime(28503): FATAL EXCEPTION: main
12-31 10:40:23.830: E/AndroidRuntime(28503): Process: com.example.bulksms, PID: 28503
12-31 10:40:23.830: E/AndroidRuntime(28503): java.lang.NullPointerException
12-31 10:40:23.830: E/AndroidRuntime(28503): at com.example.bulksms.LogoutFragment.onCreateView(LogoutFragment.java:26)
12-31 10:40:23.830: E/AndroidRuntime(28503): at android.app.Fragment.performCreateView(Fragment.java:1700)
12-31 10:40:23.830: E/AndroidRuntime(28503): at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:890)
12-31 10:40:23.830: E/AndroidRuntime(28503): at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1062)
12-31 10:40:23.830: E/AndroidRuntime(28503): at android.app.BackStackRecord.run(BackStackRecord.java:698)
12-31 10:40:23.830: E/AndroidRuntime(28503): at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1447)
12-31 10:40:23.830: E/AndroidRuntime(28503): at android.app.FragmentManagerImpl$1.run(FragmentManager.java:443)
12-31 10:40:23.830: E/AndroidRuntime(28503): at android.os.Handler.handleCallback(Handler.java:808)
12-31 10:40:23.830: E/AndroidRuntime(28503): at android.os.Handler.dispatchMessage(Handler.java:103)
12-31 10:40:23.830: E/AndroidRuntime(28503): at android.os.Looper.loop(Looper.java:193)
12-31 10:40:23.830: E/AndroidRuntime(28503): at android.app.ActivityThread.main(ActivityThread.java:5323)
12-31 10:40:23.830: E/AndroidRuntime(28503): at java.lang.reflect.Method.invokeNative(Native Method)
12-31 10:40:23.830: E/AndroidRuntime(28503): at java.lang.reflect.Method.invoke(Method.java:515)
12-31 10:40:23.830: E/AndroidRuntime(28503): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:828)
12-31 10:40:23.830: E/AndroidRuntime(28503): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:644)
12-31 10:40:23.830: E/AndroidRuntime(28503): at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:1)
在你的片段中初始化你的sessionmanager ......
session = new SessionManager(getActivity());
它会起作用......
答案 1 :(得分:1)
只需初始化您的SessionManager
课程
session = new SessionManager(getActivity());
之前打电话
session.logoutUser();
使用getActivity()
代替getApplicationContext()
。因为你使用片段。