私はAndroidアプリに取り組んでおり、登録とログインを行えるようにしたいと考えています。オンライン チュートリアルに従いましたが、問題が発生し、修正方法がわかりません。これは私の最初のAndroidアプリでもあります。ご協力いただきありがとうございます。
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.cs309.gotoclass.library.DatabaseHandler;
import com.example.cs309.gotoclass.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.activity_login_screen);
// 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(), HomeScreenStudent.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();
}
});
}
public void LoginHome(View view){
Intent intent = new Intent(this, HomeScreenStudent.class);
startActivity(intent);
}
public void LoginGuest(View view){
Intent intent = new Intent(this, HomeScreenGuest.class);
startActivity(intent);
}
}
しかし、問題は私の JSONParser クラスにあると思います
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;
}
}
そして、これが私が取得しているエラーログです
12-01 10:47:45.995: E/AndroidRuntime(21570): 致命的な例外: メイン 12-01 10:47:45.995: E/AndroidRuntime(21570): android.os.NetworkOnMainThreadException 12-01 10:47:45.995: E/AndroidRuntime(21570): android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1118) 12-01 10:47:45.995: E/AndroidRuntime(21570): java.net.InetAddress.lookupHostByName(InetAddress) .java:385) 12-01 10:47:45.995: E/AndroidRuntime(21570): java.net.InetAddress.getAllByNameImpl(InetAddress.java:236) 12-01 10:47:45.995: E/AndroidRuntime(21570) ): java.net.InetAddress.getAllByName(InetAddress.java:214) 12-01 10:47:45.995: E/AndroidRuntime(21570): org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator. java:137) 12-01 10:47:45.995: E/AndroidRuntime(21570): org.apache.http で。impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164) 12-01 10:47:45.995: E/AndroidRuntime(21570): org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119) ) 12-01 10:47:45.995: E/AndroidRuntime(21570): org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360) 12-01 10:47:45.995: E/AndroidRuntime (21570): org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:670) 12-01 10:47:45.995: E/AndroidRuntime(21570): org.apache.http.impl で。 client.AbstractHttpClient.execute(AbstractHttpClient.java:509) 12-01 10:47:45.995: E/AndroidRuntime(21570): org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487) で 12 -01 10:47:45.995: E/AndroidRuntime(21570): com.example.cs309.gotoclass.library.JSONParser.getJSONFromUrl(JSONParser.java:42) 12-01 10:47:45.995: E/AndroidRuntime(21570): com.example.cs309.gotoclass.library.UserFunctions.registerUser(UserFunctions.java:62) 12-01 10:47:45.995: E/AndroidRuntime(21570): com.example.cs309.gotoclass.RegisterActivity$1.onClick(RegisterActivity.java:55) 12-01 10:47:45.995: E/AndroidRuntime(21570): at android.view.View.performClick(View.java:4223) 12-01 10:47:45.995: E/AndroidRuntime(21570): android.view.View$PerformClick.run(View.java:17275) 12-01 10:47:45.995: E/AndroidRuntime(21570): android.os.Handler.handleCallback(Handler.java:615) 12-01 10:47:45.995: E/AndroidRuntime(21570): android.os.Handler で.dispatchMessage(Handler.java:92) 12-01 10:47:45.995: E/AndroidRuntime(21570): android.os.Looper.loop(Looper.java:137) 12-01 10:47:45.995:E/AndroidRuntime(21570): android.app.ActivityThread.main(ActivityThread.java:4898) 12-01 10:47:45.995: E/AndroidRuntime(21570): java.lang.reflect.Method.invokeNative(Nativeメソッド) 12-01 10:47:45.995: E/AndroidRuntime(21570): java.lang.reflect.Method.invoke(Method.java:511) 12-01 10:47:45.995: E/AndroidRuntime(21570) : com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006) 12-01 10:47:45.995: E/AndroidRuntime(21570): com.android.internal.os.ZygoteInit.main で(ZygoteInit.java:773) 12-01 10:47:45.995: E/AndroidRuntime(21570): dalvik.system.NativeStart.main(ネイティブ メソッド) でE/AndroidRuntime(21570): java.lang.reflect.Method.invoke(Method.java:511) 12-01 10:47:45.995: E/AndroidRuntime(21570): com.android.internal.os.ZygoteInit で$MethodAndArgsCaller.run(ZygoteInit.java:1006) 12-01 10:47:45.995: E/AndroidRuntime(21570): com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773) 12-01 10 :47:45.995: E/AndroidRuntime(21570): dalvik.system.NativeStart.main(ネイティブメソッド)E/AndroidRuntime(21570): java.lang.reflect.Method.invoke(Method.java:511) 12-01 10:47:45.995: E/AndroidRuntime(21570): com.android.internal.os.ZygoteInit で$MethodAndArgsCaller.run(ZygoteInit.java:1006) 12-01 10:47:45.995: E/AndroidRuntime(21570): com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773) 12-01 10 :47:45.995: E/AndroidRuntime(21570): dalvik.system.NativeStart.main(ネイティブメソッド)
皆さんが提供できる助けをありがとう!
アップデート:
私は AsyncTask で正しい軌道に乗っていると思いますが、まだそこにいないので、助けていただければ幸いです!
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_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.activity_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();
new RegisterTask().execute();
}
});
// 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();
}
});
}
class RegisterTask extends AsyncTask<String, String, String> {
int success;
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
String name = inputFullName.getText().toString();
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.registerUser(name, email, password);
Log.d("Create Response", json.toString());
try {
int success = json.getInt(KEY_SUCCESS);
if (success == 1) {
// DATABASE HANDLER
// 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_user.getString(KEY_UID),
json_user.getString(KEY_CREATED_AT));
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
if (success == 1) {
Intent dashboard = new Intent(getApplicationContext(), LoginActivity.class);
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
finish();
}else{
//Some Error
}
}
}
}
そして、エラーログ...
引用符
12-02 20:45:23.140: W/dalvikvm(28208): threadid=13: キャッチされない例外で終了するスレッド (group=0x415e62a0) 12-02 20:45:23.140: E/AndroidRuntime(28208): 致命的な例外: AsyncTask #1 12-02 20:45:23.140: E/AndroidRuntime(28208): java.lang.RuntimeException: doInBackground() の実行中にエラーが発生しました 12-02 20:45:23.140: E/AndroidRuntime(28208): Android で.os.AsyncTask$3.done(AsyncTask.java:299) 12-02 20:45:23.140: E/AndroidRuntime(28208): java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273) で 12 -02 20:45:23.140: E/AndroidRuntime(28208): java.util.concurrent.FutureTask.setException(FutureTask.java:124) 12-02 20:45:23.140: E/AndroidRuntime(28208): Java で.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307) 12-02 20:45:23.140: E/AndroidRuntime(28208): java.util.concurrent で。FutureTask.run(FutureTask.java:137) 12-02 20:45:23.140: E/AndroidRuntime(28208): android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 12-02 20:45 :23.140: E/AndroidRuntime(28208): java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076) 12-02 20:45:23.140: E/AndroidRuntime(28208): java.util.concurrent で。 ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569) 12-02 20:45:23.140: E/AndroidRuntime(28208): java.lang.Thread.run(Thread.java:856) 12-02 20:45: 23.140: E/AndroidRuntime(28208): 原因: java.lang.NullPointerException 12-02 20:45:23.140: E/AndroidRuntime(28208): com.example.cs309.gotoclass.RegisterActivity$RegisterTask.doInBackground(RegisterActivity. java:89) 12-02 20:45:23.140: E/AndroidRuntime(28208): com.example.cs309.gotoclass.RegisterActivity$RegisterTask.doInBackground(RegisterActivity.java:1) 12-02 20:45:23.140: E/AndroidRuntime(28208): android.os.AsyncTask$2.call(AsyncTask.java:287) 12-02 20:45:23.140: E /AndroidRuntime(28208): java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305) で