Android应用程序意外停止

时间:2015-05-07 16:20:00

标签: java android

  Logcat error
   05-07 23:57:26.990: E/JSON Parser(1297): Error parsing data org.json.JSONException: Value ???<br of type java.lang.String cannot be converted to JSONObject 
05-07 23:57:27.000: E/AndroidRuntime(1297): FATAL EXCEPTION: AsyncTask #1
05-07 23:57:27.000: E/AndroidRuntime(1297): java.lang.RuntimeException: An error occured while executing doInBackground()
05-07 23:57:27.000: E/AndroidRuntime(1297):at android.os.AsyncTask$3.done(AsyncTask.java:200)
 05-07 23:57:27.000: E/AndroidRuntime(1297):    at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274)

我正在开发一个登录Android应用程序..i遇到一个问题,当在模拟器或Android设备上单击登录按钮时应用程序意外停止。因为我使用正确的IP地址并连接正确的wampserver数据库..可能我知道什么即使我重启eclipse也是错误。

这里是JSONParser.java类

import android.util.Log;
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;


public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}


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;

}


// 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;

}
}

这是login.java编码

package com.example.testpsm1;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

 public class Login extends Activity implements OnClickListener{

private EditText user, pass;
private Button mSubmit;

 // Progress Dialog
private ProgressDialog pDialog;

// JSON parser class
JSONParser jsonParser = new JSONParser();

//php login script location:

//localhost :  
//testing on your device
//put your local ip instead,  on windows, run CMD > ipconfig
//or in mac's terminal type ifconfig and look for the ip under en0 or en1

//testing on Emulator:
private static final String LOGIN_URL = "http://192.168.1.9/webservice/login.php";



//JSON element ids from repsonse of php script:
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    //setup input fields
    user = (EditText)findViewById(R.id.email);
    pass = (EditText)findViewById(R.id.password);

    //setup buttons
    mSubmit = (Button)findViewById(R.id.login);


    //register listeners
    mSubmit.setOnClickListener(this);


}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub

            new AttemptLogin().execute();

}

class AttemptLogin extends AsyncTask<String, String, String> {

     /**
     * Before starting background thread Show Progress Dialog
     * */
    boolean failure = false;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(Login.this);
        pDialog.setMessage("Attempting login...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected String doInBackground(String... args) {
        // TODO Auto-generated method stub
         // Check for success tag
        int success;
        String username = user.getText().toString();
        String password = pass.getText().toString();
        try {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("username", username));
            params.add(new BasicNameValuePair("password", password));

            Log.d("request!", "starting");
            // getting product details by making HTTP request
            JSONObject json = jsonParser.makeHttpRequest(
                   LOGIN_URL, "POST", params);

            // check your log for json response
            Log.d("Login attempt", json.toString());

            // json success tag
            success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
                Log.d("Login Successful!", json.toString());
                Intent i = new Intent(Login.this, ReadComments.class);
                finish();
                startActivity(i);
                return json.getString(TAG_MESSAGE);
            }else{
                Log.d("Login Failure!", json.getString(TAG_MESSAGE));
                return json.getString(TAG_MESSAGE);

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;

    }
    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog once product deleted
        pDialog.dismiss();
        if (file_url != null){
            Toast.makeText(Login.this, file_url, Toast.LENGTH_LONG).show();
        }

    }

}


}

这是login.java编码

<RelativeLayout 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"
>


<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="17dp"
android:gravity="center"
android:text="Mobile Attendance System"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textStyle="bold" />

<EditText
 android:id="@+id/email"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_alignBaseline="@+id/textView1"
 android:layout_alignBottom="@+id/textView1"
 android:layout_alignParentRight="true"
   android:layout_marginTop="70dp"
 android:ems="10" />

 <EditText
  android:id="@+id/password"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_alignBottom="@+id/TextView01"
 android:layout_alignLeft="@+id/login"
 android:layout_alignTop="@+id/TextView01"
 android:ems="10"
 android:inputType="textPassword" >

 <requestFocus />
 </EditText>

 <Button
 android:id="@+id/login"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_centerVertical="true"
 android:layout_toRightOf="@+id/textView1"
 android:text="Login" />

<TextView
 android:id="@+id/TextView01"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_below="@+id/textView1"
 android:layout_marginTop="20dp"
 android:layout_toLeftOf="@+id/editText1"
 android:text="Password"
 android:textSize="20dp" />

 <TextView
 android:id="@+id/textView1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_alignParentLeft="true"
 android:layout_below="@+id/textView2"
 android:layout_marginTop="34dp"
 android:text="Username"
 android:textSize="20dp" />

</RelativeLayout>

2 个答案:

答案 0 :(得分:0)

返回的数据不包含有效的JSON对象。从摘录中猜测,它们也不在ISO 8859-1中。

答案 1 :(得分:0)

在查看堆栈跟踪后,我发现您的Web Api响应正在返回
无法解析为Jason对象的标签。从服务器返回的响应是错误的检查。