我是Android新手,我正在尝试制作一个像Sales App这样的简单应用。当我在模拟器中运行应用程序时,它会显示消息:
不幸的是,销售已停止。
这是我的登录
package com.stmik.slidingmenu.utama;
import org.json.JSONException;
import org.json.JSONObject;
import com.stmik.slidingmenu.R;
import com.stmik.slidingmenu.library.DatabaseHandler;
import com.stmik.slidingmenu.library.UserFunctions;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
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 = "kode";
private static String KEY_NAME = "nama";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "dibuat_tgl";
@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();
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();
}
});
}
}
这是我的用户功能
package com.stmik.slidingmenu.library;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import android.content.Context;
public class UserFunctions {
private JSONParser jsonParser;
// Testing in localhost using wamp or xampp
// use http://10.0.2.2/ to connect to your localhost ie http://localhost/
private static String loginURL = "http://192.168.0.100/sales_app/";
private static String registerURL = "http://192.168.0.100/sales_app/";
private static String login_tag = "login";
private static String register_tag = "register";
// constructor
public UserFunctions(){
jsonParser = new JSONParser();
}
/**
* function make Login Request
* @param email
* @param password
* */
public JSONObject loginUser(String email, String password){
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", login_tag));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));
JSONObject json = jsonParser.getJSONFromUrl(loginURL, params);
// return json
// Log.e("JSON", json.toString());
return json;
}
/**
* function make Login Request
* @param name
* @param email
* @param password
* */
public JSONObject registerUser(String nama, String email, String password){
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", register_tag));
params.add(new BasicNameValuePair("nama", nama));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));
// getting JSON Object
JSONObject json = jsonParser.getJSONFromUrl(registerURL, params);
// return json
return json;
}
/**
* Function get Login status
* */
public boolean isUserLoggedIn(Context context){
DatabaseHandler db = new DatabaseHandler(context);
int count = db.getRowCount();
if(count > 0){
// user logged in
return true;
}
return false;
}
/**
* Function to logout user
* Reset Database
* */
public boolean logoutUser(Context context){
DatabaseHandler db = new DatabaseHandler(context);
db.resetTables();
return true;
}
}
这是我的json
package com.stmik.slidingmenu.library;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
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.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "n");
}
is.close();
json = sb.toString();
Log.e("JSON", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
这里是logcat
05-25 07:40:47.450: D/dalvikvm(837): GC_FOR_ALLOC freed 51K, 7% free 2570K/2744K, paused 47ms, total 50ms
05-25 07:40:47.460: I/dalvikvm-heap(837): Grow heap (frag case) to 3.232MB for 635812-byte allocation
05-25 07:40:47.520: D/dalvikvm(837): GC_FOR_ALLOC freed 5K, 6% free 3186K/3368K, paused 53ms, total 53ms
05-25 07:40:47.600: D/dalvikvm(837): GC_CONCURRENT freed <1K, 5% free 3203K/3368K, paused 39ms+4ms, total 81ms
05-25 07:40:55.924: I/Choreographer(837): Skipped 48 frames! The application may be doing too much work on its main thread.
05-25 07:40:56.094: D/gralloc_goldfish(837): Emulator without GPU emulation detected.
05-25 07:40:56.424: I/Choreographer(837): Skipped 45 frames! The application may be doing too much work on its main thread.
05-25 07:40:58.764: D/AndroidRuntime(837): Shutting down VM
05-25 07:40:58.794: W/dalvikvm(837): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
05-25 07:40:58.844: E/AndroidRuntime(837): FATAL EXCEPTION: main
05-25 07:40:58.844: E/AndroidRuntime(837): android.os.NetworkOnMainThreadException
05-25 07:40:58.844: E/AndroidRuntime(837): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
05-25 07:40:58.844: E/AndroidRuntime(837): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
05-25 07:40:58.844: E/AndroidRuntime(837): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
05-25 07:40:58.844: E/AndroidRuntime(837): at libcore.io.IoBridge.connect(IoBridge.java:112)
05-25 07:40:58.844: E/AndroidRuntime(837): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
05-25 07:40:58.844: E/AndroidRuntime(837): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
05-25 07:40:58.844: E/AndroidRuntime(837): at java.net.Socket.connect(Socket.java:842)
05-25 07:40:58.844: E/AndroidRuntime(837): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
05-25 07:40:58.844: E/AndroidRuntime(837): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
05-25 07:40:58.844: E/AndroidRuntime(837): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
05-25 07:40:58.844: E/AndroidRuntime(837): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
05-25 07:40:58.844: E/AndroidRuntime(837): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
05-25 07:40:58.844: E/AndroidRuntime(837): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
05-25 07:40:58.844: E/AndroidRuntime(837): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
05-25 07:40:58.844: E/AndroidRuntime(837): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
05-25 07:40:58.844: E/AndroidRuntime(837): at com.stmik.slidingmenu.library.JSONParser.getJSONFromUrl(JSONParser.java:42)
05-25 07:40:58.844: E/AndroidRuntime(837): at com.stmik.slidingmenu.library.UserFunctions.loginUser(UserFunctions.java:40)
05-25 07:40:58.844: E/AndroidRuntime(837): at com.stmik.slidingmenu.utama.LoginActivity$1.onClick(LoginActivity.java:55)
05-25 07:40:58.844: E/AndroidRuntime(837): at android.view.View.performClick(View.java:4204)
05-25 07:40:58.844: E/AndroidRuntime(837): at android.view.View$PerformClick.run(View.java:17355)
05-25 07:40:58.844: E/AndroidRuntime(837): at android.os.Handler.handleCallback(Handler.java:725)
05-25 07:40:58.844: E/AndroidRuntime(837): at android.os.Handler.dispatchMessage(Handler.java:92)
05-25 07:40:58.844: E/AndroidRuntime(837): at android.os.Looper.loop(Looper.java:137)
05-25 07:40:58.844: E/AndroidRuntime(837): at android.app.ActivityThread.main(ActivityThread.java:5041)
05-25 07:40:58.844: E/AndroidRuntime(837): at java.lang.reflect.Method.invokeNative(Native Method)
05-25 07:40:58.844: E/AndroidRuntime(837): at java.lang.reflect.Method.invoke(Method.java:511)
05-25 07:40:58.844: E/AndroidRuntime(837): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
05-25 07:40:58.844: E/AndroidRuntime(837): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
05-25 07:40:58.844: E/AndroidRuntime(837): at dalvik.system.NativeStart.main(Native Method)
05-25 07:45:59.016: I/Process(837): Sending signal. PID: 837 SIG: 9
和php代码
class DB_Functions {
private $db;
//put your code here
// constructor
function __construct() {
require_once 'DB_Connect.php';
// connecting to database
$this->db = new DB_Connect();
$this->db->connect();
}
// destructor
function __destruct() {
}
/**
* Storing new user
* returns user details
*/
public function storeUser($nama_sales, $email_sales, $password_sales, $alamat_sales, $hp_sales, $telp_sales) {
$uuid_sales = uniqid('', true);
$result = mysql_query("INSERT INTO m_sales(unique_id_sales, nama_sales, email_sales, password_sales, alamat_sales, hp_sales, telp_sales, dibuat_tgl) VALUES('$uuid_sales', '$nama_sales', '$email_sales', '$password_sales','$alamat_sales', '$hp_sales', '$telp_sales', NOW())");
// check for successful store
if ($result) {
// get user details
$uid_sales = mysql_insert_id(); //last inserted id
$result = mysql_query("SELECT * FROM m_sales WHERE uid_sales = $uid_sales");
// return user details
return mysql_fetch_array($result);
} else {
return false;
}
}
/**
* Get user by email_sales and password_sales
*/
public function getUserByEmailAndPassword($email_sales, $password_sales) {
$result = mysql_query("SELECT * FROM m_sales WHERE email_sales = '$email_sales'") or die(mysql_error());
// check for result
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
$result = mysql_fetch_array($result);
$password_sales = $result['password_sales'];
} else {
// user not found
return false;
}
}
/**
* Check user is existed or not
*/
public function isUserExisted($email_sales) {
$result = mysql_query("SELECT email_sales from m_sales WHERE email_sales = '$email_sales'");
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
// user existed
return true;
} else {
// user not existed
return false;
}
}
我该如何解决这个问题?
答案 0 :(得分:1)
看看:
https://stackoverflow.com/a/6986726/1836697
logcat的重要部分是
android.os.NetworkOnMainThreadException
不允许在主线程上运行网络线程。使用单独的线程来执行网络任务,你应该没事。
答案 1 :(得分:0)
您无法在主线程上执行网络操作。尝试将网络代码包装在新线程中或使用AsyncTask。