不要没有问题,只是每次我输入用户名和密码 对话框显示尝试登录和应用程序崩溃。 使用的服务器:Wamp 以下是使用的代码。 任何帮助都会很明显。谢谢。
LoginActivity.java:
package com.sam.kiet;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.util.Log;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Vaibhav on 10/2/2015.
*/
public class LoginActivity extends Activity implements View.OnClickListener {
private EditText user, pass;
private Button bLogin;
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "http://192.168.43.1/login.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
user = (EditText) findViewById(R.id.username);
pass = (EditText) findViewById(R.id.password);
bLogin = (Button) findViewById(R.id.Blogin);
bLogin.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.Blogin:
new AttemptLogin().execute();
default:
break;
}
}
class AttemptLogin extends AsyncTask<String, String, String> {
//boolean failure = false;
private String username,password;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginActivity.this);
pDialog.setMessage("Attempting for login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
username = user.getText().toString();
password = pass.getText().toString();
}
@Override
protected String doInBackground(String... args) {
int success;
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("request!", "starting");
JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST", params);
Log.d("Login attempt", json.toString());
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Successfully Login!", json.toString());
Intent main_activity = new Intent(LoginActivity.this, MainActivity.class);
finish();
startActivity(main_activity);
return json.getString(TAG_MESSAGE);
} else {
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String message) {
super.onPostExecute(message);
pDialog.dismiss();
if (message != null){
Toast.makeText(LoginActivity.this, message, Toast.LENGTH_LONG).show();
}
}
}
}
JasonParsor.java:
package com.sam.kiet;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
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() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// 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();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
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();
} 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;
}
public JSONObject getJSONFromUrl(final String url) {
// Making HTTP request
try {
// Construct the client and the HTTP request.
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
// Execute the POST request and store the response locally.
HttpResponse httpResponse = httpClient.execute(httpPost);
// Extract data from the response.
HttpEntity httpEntity = httpResponse.getEntity();
// Open an inputStream with the data content.
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
// Create a BufferedReader to parse through the inputStream.
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
// Declare a string builder to help with the parsing.
StringBuilder sb = new StringBuilder();
// Declare a string to store the JSON object data in string form.
String line = null;
// Build the string until null.
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
// Close the input stream.
is.close();
// Convert the string builder data to an actual string.
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// Try to 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 the JSON Object.
return jObj;
}
}
Login.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
android:paddingBottom="16dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
tools:context=".LoginActivity"
>
<!-- Login progress -->
<ProgressBar
android:id="@+id/login_progress" style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:visibility="gone"
/>
<ScrollView
android:id="@+id/login_form"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<LinearLayout
android:id="@+id/email_login_form"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<AutoCompleteTextView
android:id="@+id/username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Username"
android:inputType="text"
android:maxLines="1"
android:singleLine="true" />
<EditText android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Password"
android:imeActionId="@+id/login"
android:imeActionLabel="Login"
android:imeOptions="actionUnspecified"
android:inputType="textPassword"
android:maxLines="1"
android:singleLine="true" />
<Button
android:id="@+id/Blogin"
style="?android:textAppearanceSmall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Login"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
</ScrollView>
logcat的(错误):
10-12 09:02:22.084 1804-1819/com.sam.kiet E/Buffer Error﹕ Error converting
result java.lang.NullPointerException: lock == null
10-12 09:02:22.084 1804-1819/com.sam.kiet E/JSON Parser﹕ Error parsing data org.json.JSONException: End of input at character 0 of
10-12 09:02:22.094 1804-1819/com.sam.kiet E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #2
Process: com.sam.kiet, PID: 1804
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.NullPointerException
at com.sam.kiet.LoginActivity$AttemptLogin.doInBackground(LoginActivity.java:92)
at com.sam.kiet.LoginActivity$AttemptLogin.doInBackground(LoginActivity.java:60)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
10-12 09:02:23.744 1804-1804/com.sam.kiet E/WindowManager﹕ android.view.WindowLeaked: Activity com.sam.kiet.LoginActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{b1402280 V.E..... R......D 0,0-1026,288} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:346)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:286)
at com.sam.kiet.LoginActivity$AttemptLogin.onPreExecute(LoginActivity.java:71)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
at android.os.AsyncTask.execute(AsyncTask.java:535)
at com.sam.kiet.LoginActivity.onClick(LoginActivity.java:53)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
新LOGCAT:
10-12 10:40:56.083 5644-5658/com.sam.kiet E/JSON Parser﹕ Error parsing data org.json.JSONException: Value success of type java.lang.String cannot be converted to JSONObject
10-12 10:40:56.093 5644-5658/com.sam.kiet E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #2
Process: com.sam.kiet, PID: 5644
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.NullPointerException
at com.sam.kiet.LoginActivity$AttemptLogin.doInBackground(LoginActivity.java:85)
at com.sam.kiet.LoginActivity$AttemptLogin.doInBackground(LoginActivity.java:60)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
10-12 10:40:58.003 5644-5644/com.sam.kiet E/WindowManager﹕ android.view.WindowLeaked: Activity com.sam.kiet.LoginActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{b1401ef8 V.E..... R......D 0,0-1026,288} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:346)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:286)
at com.sam.kiet.LoginActivity$AttemptLogin.onPreExecute(LoginActivity.java:71)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
at android.os.AsyncTask.execute(AsyncTask.java:535)
at com.sam.kiet.LoginActivity.onClick(LoginActivity.java:53)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:5)
好吧我认为你得到的是NullPointer:
if(method == "POST"){
将其更改为
if("POST".equals(method)){
您将对象引用与==
的值进行比较。
这就是方法makeHttpRequest
返回null
的原因。
当然你也必须改变它:
}else if(method == "GET"){
答案 1 :(得分:3)
这部分代码
Intent main_activity = new Intent(LoginActivity.this, MainActivity.class);
finish();
startActivity(main_activity);
return json.getString(TAG_MESSAGE);
您创建Intent
然后finish()
活动,然后运行startActivity()
并最终返回。
逻辑顺序错误,尝试这种方法:
class AttemptLogin extends AsyncTask<String, String, JSONObject> {
//boolean failure = false;
private String username,password;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LoginActivity.this);
pDialog.setMessage("Attempting for login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
username = user.getText().toString();
password = pass.getText().toString();
}
@Override
protected JSONObject doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("request!", "starting");
JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST", params);
Log.d("Login attempt", json.toString());
return json;
}
@Override
protected void onPostExecute(JSONObject json) {
super.onPostExecute(json);
pDialog.dismiss();
if (json != null){
try {
int success = json.getInt(TAG_SUCCESS);
String message = json.getString(TAG_MESSAGE);
if (success == 1) {
Log.d("Successfully Login!", json.toString());
Toast.makeText(LoginActivity.this,"Login successful" + message, Toast.LENGTH_LONG).show();
Intent main_activity = new Intent(LoginActivity.this, MainActivity.class);
startActivity(main_activity);
finish();//only at the end!!!
} else {
Toast.makeText(LoginActivity.this, "Login failed = " + message, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
答案 2 :(得分:0)
尝试更改
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
到
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data",e);
} catch (Exception e) {
Log.e("JSON Parser", "Error parsing data",e);
}
我的猜测是你得到一个JSONException没有捕获的空指针异常。
一般情况下,我建议在try-&gt; catch之前检查null对象,因为它的价格更便宜&#34;比try-&gt; catch机制(非常昂贵&#34;)。
答案 3 :(得分:0)
JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST", params);
将此更改为此
JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "GET", params);
你收到错误是因为你没有得到Json所以改变你的类型并再次调用方法
答案 4 :(得分:0)
观察您的代码和logcat报告......
最初你有一个错误,将你用try catch处理的InputStream转换为String ,因为Log.e("Buffer Error", "Error converting result " + e.toString());
你可以在第一个logcat报告中看到它。此错误是InputStream is
的NPE。但最后你的方法返回null jsonObject这会导致传播多个错误
解决方案修复此问题由@Stefan Beike提供,答案是错误的字符串比较
现在你的json形成有错误,所以你在下面的代码中提到了错误
try {
jObj = new JSONObject(json); //LINE THROWING ERROR...
//check properly String json if properly formatted json....so request for String json in question
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
//Above line is visible in the second logcat report i.e new logcat.
}
但是你的方法再次返回jObj,这是null ...所以在你的doInBackground中你再次遇到多个错误 从新的logcat报告
Error parsing data org.json.JSONException: Value success of type java.lang.String cannot be converted to JSONObject
所以,如果你想与其他程序员有更多的帮助,那么我会要求 你转换InputStream后发布json字符串即字符串 有问题的字符串。或者你自己可以检查字符串是否格式正确JSON。