我想从登录活动访问确认活动。当我没有登录和注册活动时,我能够启动确认活动。登录和注册工作完美,没有确认活动。和仪表板活动和确认活动完美无需登录和注册活动。
Registration Activity.
package com.example.androidhive;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.androidhive.library.DatabaseHandler;
import com.example.androidhive.library.UserFunctions;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class RegisterActivity extends Activity {
Button btnRegister;
Button btnLinkToLogin;
EditText inputFullName;
EditText inputEmail;
EditText inputPassword;
TextView registerErrorMsg;
// JSON Response node names
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_UID = "uid";
private static String KEY_NAME = "name";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
// Importing all assets like buttons, text fields
inputFullName = (EditText) findViewById(R.id.registerName);
inputEmail = (EditText) findViewById(R.id.registerEmail);
inputPassword = (EditText) findViewById(R.id.registerPassword);
btnRegister = (Button) findViewById(R.id.btnRegister);
btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);
registerErrorMsg = (TextView) findViewById(R.id.register_error);
// Register Button Click event
btnRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String name = inputFullName.getText().toString();
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.registerUser(name, email, password);
// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
registerErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// user successfully registred
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
// Clear all previous data in database
userFunction.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));
// Launch Dashboard Screen
Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class);
// Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
// Close Registration Screen
finish();
}else{
// Error in registration
registerErrorMsg.setText("Error occured in registration");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
// Link to Login Screen
btnLinkToLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
LoginActivity.class);
startActivity(i);
// Close Registration View
finish();
}
});
}
}
Login Activity:-
import java.util.HashMap;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.example.androidhive.library.DatabaseHandler;
import com.example.androidhive.library.UserFunctions;
public class LoginActivity extends Activity {
Button btnLogin;
Button btnLinkToRegister;
EditText inputEmail;
EditText inputPassword;
TextView loginErrorMsg;
// JSON Response node names
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_UID = "uid";
private static String KEY_NAME = "name";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
// Importing all assets like buttons, text fields
inputEmail = (EditText) findViewById(R.id.loginEmail);
inputPassword = (EditText) findViewById(R.id.loginPassword);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
loginErrorMsg = (TextView) findViewById(R.id.login_error);
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
UserFunctions userFunction = new UserFunctions();
Log.d("Button", "Login");
JSONObject json = userFunction.loginUser(email, password);
// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
loginErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// user successfully logged in
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
// Clear all previous data in database
userFunction.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));
// Launch Dashboard Screen
Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class);
// Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
// Close Login Screen
finish();
}else{
// Error in login
loginErrorMsg.setText("Incorrect username/password");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
// Link to Register Screen
btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
finish();
}
});
}
}
Dashboard Activity:-
package com.example.androidhive;
import android.app.Activity;
import com.example.androidhive.ConfirmationActivity;
import com.example.androidhive.R;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.Toast;
import android.widget.Button;
import com.example.androidhive.library.UserFunctions;
public class DashboardActivity extends Activity {
UserFunctions userFunctions;
Button btnLogout;
private String resultString="";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/**
* Dashboard Screen for the application
* */
// Check login status in database
userFunctions = new UserFunctions();
if(userFunctions.isUserLoggedIn(getApplicationContext())){
setContentView(R.layout.dashboard);
btnLogout = (Button) findViewById(R.id.btnLogout);
btnLogout.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
userFunctions.logoutUser(getApplicationContext());
Intent login = new Intent(getApplicationContext(), LoginActivity.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(login);
// Closing dashboard screen
finish();
}
});
}else{
// user is not logged in show login screen
Intent login = new Intent(getApplicationContext(), LoginActivity.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(login);
// Closing dashboard screen
finish();
}
}
public class WebAppInterface {
Context mContext;
/** Instantiate the interface and set the context */
WebAppInterface(Context c) {
mContext = c;
}
/** Show a toast from the web page */
@JavascriptInterface
public void showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode==0)
if (resultCode == RESULT_OK) {
//Use Data to get string
resultString = data.getStringExtra("RESULT_STRING");
LaunchWebView(resultString);
}
super.onActivityResult(requestCode, resultCode, data);
}
private void LaunchWebView(String resultString)
{
WebView engine=(WebView)findViewById(com.example.androidhive.R.id.web_engine);
//engine.getSettings().setJavaScriptEnabled(true);
String[] array=resultString.split(":");
engine.getSettings().setLoadsImagesAutomatically(true);
//engine.getSettings().setBuiltInZoomControls(true);
engine.getSettings().setUseWideViewPort(true);
engine.setWebChromeClient(new MyJavaScriptChromeClient());
engine.loadUrl("http://74.101.168.139/snapshot.cgi?user="+array[0]+"&pwd="+array[1]+"&count=0" + "&resolution=32"+ "&rate=6");
}
public void btnRefresh_ClicHandler(View view)
{
if(resultString!="")
LaunchWebView(resultString);
}
public void btnHome(View arg)
{
Intent intent=new Intent(this,ConfirmationActivity.class);
int result=0;
startActivityForResult(intent, result);
}
private class MyJavaScriptChromeClient extends WebChromeClient {
@Override
public boolean onJsAlert(WebView view, String url, String message,
JsResult result) {
// TODO Auto-generated method stub
return super.onJsAlert(view, null, message, result);
}
}
}
Confirmation Activity : -
package com.example.androidhive;
import com.example.androidhive.R;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class ConfirmationActivity extends Activity {
EditText txtPassword=null;
EditText txtUsername=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_confirmation);
}
public static final class menu2 {
public static final int confirmation=0x7f080000;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(menu2.confirmation, menu);
return true;
}
public void btnCancel_ClickHandler(View arg)
{
finish();
}
public void btnOk_ClickHandler(View arg)
{
txtUsername=(EditText)findViewById(com.example.androidhive.R.id.txtUserName);
txtPassword=(EditText)findViewById(com.example.androidhive.R.id.txtPassword);
if(txtUsername.getText().length()==0)
{
Toast.makeText(getApplicationContext(),
"User name can not be empty.", Toast.LENGTH_LONG).show();
return;
}
if(txtPassword.getText().length()==0)
{
Toast.makeText(getApplicationContext(),
"Password can not be empty.", Toast.LENGTH_LONG).show();
return;
}
Intent intent=new Intent();
intent.putExtra("RESULT_STRING",txtUsername.getText()+ ":"+txtPassword.getText());
setResult(RESULT_OK, intent);
finish();
}
}
Android Manifest.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.androidhive"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8"
android:targetSdkVersion="18"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:label="@string/app_name"
android:name=".DashboardActivity" >
</activity>
<!-- Confirmation Activity -->
<activity
android:label="Confiramtion Activity"
android:name=".ConfiramtionActivity"></activity>
<!-- Login Activity -->
<activity
android:label="Login Account"
android:name=".LoginActivity"></activity>
<!-- Register Activity -->
<activity
android:label="Register New Account"
android:name=".RegisterActivity">
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Android Fatal Error PLeaseeee Help:-
11-15 16:55:40.948: E/AndroidRuntime(858): FATAL EXCEPTION: main
11-15 16:55:40.948: E/AndroidRuntime(858): android.os.NetworkOnMainThreadException
11-15 16:55:40.948: E/AndroidRuntime(858): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
11-15 16:55:40.948: E/AndroidRuntime(858): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
11-15 16:55:40.948: E/AndroidRuntime(858): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
11-15 16:55:40.948: E/AndroidRuntime(858): at libcore.io.IoBridge.connect(IoBridge.java:112)
11-15 16:55:40.948: E/AndroidRuntime(858): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
11-15 16:55:40.948: E/AndroidRuntime(858): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
11-15 16:55:40.948: E/AndroidRuntime(858): at java.net.Socket.connect(Socket.java:842)
11-15 16:55:40.948: E/AndroidRuntime(858): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
11-15 16:55:40.948: E/AndroidRuntime(858): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
11-15 16:55:40.948: E/AndroidRuntime(858): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
11-15 16:55:40.948: E/AndroidRuntime(858): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
11-15 16:55:40.948: E/AndroidRuntime(858): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
11-15 16:55:40.948: E/AndroidRuntime(858): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
11-15 16:55:40.948: E/AndroidRuntime(858): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
11-15 16:55:40.948: E/AndroidRuntime(858): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
11-15 16:55:40.948: E/AndroidRuntime(858): at com.example.androidhive.library.JSONParser.getJSONFromUrl(JSONParser.java:47)
11-15 16:55:40.948: E/AndroidRuntime(858): at com.example.androidhive.library.UserFunctions.loginUser(UserFunctions.java:32)
11-15 16:55:40.948: E/AndroidRuntime(858): at com.example.androidhive.LoginActivity$1.onClick(LoginActivity.java:61)
11-15 16:55:40.948: E/AndroidRuntime(858): at android.view.View.performClick(View.java:4240)
11-15 16:55:40.948: E/AndroidRuntime(858): at android.view.View$PerformClick.run(View.java:17721)
11-15 16:55:40.948: E/AndroidRuntime(858): at android.os.Handler.handleCallback(Handler.java:730)
11-15 16:55:40.948: E/AndroidRuntime(858): at android.os.Handler.dispatchMessage(Handler.java:92)
11-15 16:55:40.948: E/AndroidRuntime(858): at android.os.Looper.loop(Looper.java:137)
11-15 16:55:40.948: E/AndroidRuntime(858): at android.app.ActivityThread.main(ActivityThread.java:5103)
11-15 16:55:40.948: E/AndroidRuntime(858): at java.lang.reflect.Method.invokeNative(Native Method)
11-15 16:55:40.948: E/AndroidRuntime(858): at java.lang.reflect.Method.invoke(Method.java:525)
11-15 16:55:40.948: E/AndroidRuntime(858): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-15 16:55:40.948: E/AndroidRuntime(858): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-15 16:55:40.948: E/AndroidRuntime(858): at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:0)
当应用程序尝试访问主线程中的网络时,抛出此异常。这是禁止的,因为通过网络访问资源可能会花费无限的时间,您的主线程将被阻止,直到网络操作完成,从而使您的应用程序冻结给用户。
相反,在您的onClick()
方法中,您应该开始一个新的AsyncTask来进行网络连接。任务完成后,继续更新ui(更改活动等)。