无法在Android的应用程序(第一页)的登录页面中实现json解析

时间:2013-02-13 11:23:56

标签: android json

我是Android编程新手。我已经浏览了Google的大多数Android开发人员文档。这是我的问题:

我想做的事情:从我的应用程序的第一个登录页面,我正在尝试获取位于服务器中的json文件并解析结果以检查登录是否成功。 我无法在下面的类中解析json。请说明出了什么问题。我已经检查了过去几天在stackoverflow上的所有其他问题,但没有多少帮助。请帮忙。

LoginActivity.java

package com.practice.serverdashboard;



import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.Service;
import android.content.Context;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

public class LoginActivity extends Activity {

    public EditText username;
    private EditText password;

    private static final String TAG = "MyActivity";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        username = (EditText) findViewById(R.id.txt_username);   
        password = (EditText) findViewById(R.id.txt_password);   

        //Showing the keypad
         InputMethodManager mgr = (InputMethodManager)this.getSystemService(Service.INPUT_METHOD_SERVICE);
         mgr.showSoftInput(username, InputMethodManager.SHOW_IMPLICIT);     
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_login, menu);
        return true;
    }


    public void callLoginService(View v)
    {
        //Hidding the keypad
        InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        mgr.hideSoftInputFromWindow(username.getWindowToken(), 0);
        mgr.hideSoftInputFromWindow(password.getWindowToken(), 0);


        String loginUrlString="http://freakageekinternaltest.com:2200/mgmt/JSP/login.jsp?userId="+username.getText()+"&pws="+password.getText();
        Log.e("log_tag", "The URL is :: "+loginUrlString);
        //calling the login URL
        //GetJson gJ=new GetJson();
        //gJ.execute(loginUrlString);
        JSONObject json=getJSONfromURL(loginUrlString);


        AlertDialog.Builder adb = new AlertDialog.Builder(
                LoginActivity.this);
                adb.setTitle("Login Service");
                adb.setMessage("Testing...");
                adb.setPositiveButton("Ok", null);
                adb.show(); 


    }



public JSONObject getJSONfromURL(String url){

    //initialize
    InputStream is = null;
    String result = "";
    JSONObject jArray = null;

    //http post
    try{
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();

    }catch(Exception e){
        Log.e("log_tag", "Error in http connection "+e.toString());
    }

    //convert response to string
    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();
        result=sb.toString();

        Log.e("log_tag", "result is:: "+result);

    }catch(Exception e){
        Log.e("log_tag", "Error converting result "+e.toString());
    }

    //try parse the string to a JSON object
    try{
            jArray = new JSONObject(result);
    }catch(JSONException e){
        Log.e("log_tag", "Error parsing data "+e.toString());
    }

    AlertDialog.Builder adb = new AlertDialog.Builder(
            LoginActivity.this);
            adb.setTitle("Login Service");
            adb.setMessage("Success...");
            adb.setPositiveButton("Ok", null);
            adb.show(); 

    return jArray;
}

}

这是logcat输出:

02-13 11:13:15.173: E/log_tag(6083): The URL is :: http://freakageekinternaltest.com:2200/mgmt/JSP/login.jsp?userId=test567&pws=test@pps
02-13 11:13:15.183: E/log_tag(6083): Error in http connection android.os.NetworkOnMainThreadException
02-13 11:13:15.183: E/log_tag(6083): Error converting result java.lang.NullPointerException: lock == null
02-13 11:13:15.183: E/log_tag(6083): Error parsing data org.json.JSONException: End of input at character 0 of 

我也检查了AsyncTask,因为NetworkOnMainThreadException异常(来自stackoverflow的帮助)。但我不知道从哪里开始以及如何在我的LoginActivity.java类中使用Async类。请帮忙。在先生的帮助下感谢你。

这是我试图从服务器获取并解析的json:

{"LOGIN":"TRUE","userId":"Web Administrator","userAccessType":"ALL"}

@gabe:thx for ur early reply gabe。是否必须在后台进行网络操作?由于我试图从服务器获取登录详细信息,当它只是坐在那里等待服务器响应时我的应用程序会做什么?另外,考虑到我上面的代码,如何实现AsyncTask类?我已经浏览了你提到的文档。但我尝试创建一个扩展AsyncTask的新类。在该类中,我在doInBackground方法中执行了所有网络操作,并使用onPostExecute方法将结果发送回LoginActivity.java类。但是,由于此后台操作是在扩展AsyncTask类的新类上完成的,因此我无法使用main_activity.xml文件中定义的控件。那么如何实现这一切呢?再一次。

再次问好! 现在我按照答案中的建议修改了我的代码。

private class RetreiveDataAsynctask extends AsyncTask<String,Void,JSONObject> {

        @Override
        protected JSONObject doInBackground(String... loginURL) {
            JSONObject obj = getJSONfromURL(loginURL);
            return obj;
        }

        @Override
        protected void onPostExecute(JSONObject obj) {
             //Do all ur UI related stuff as this will be executing in ui thread

            super.onPostExecute(obj);
        }


    }

在onCreate方法中,我这样称呼:

RetreiveDataAsynctask mRetreiveData = new RetreiveDataAsynctask();
        mRetreiveData.execute(loginUrlString);

但是,它在这一行中给出错误:

JSONObject obj = getJSONfromURL(loginURL);

有人可以告诉我这段代码有什么问题吗?其余的解析函数与上面指定的相同。 Thx提前。

4 个答案:

答案 0 :(得分:1)

错误

Error in http connection android.os.NetworkOnMainThreadException

表示您正在主线程上进行工作,但是您应该在单独的线程中执行此操作,因为您的网络操作会阻止用户界面

您可以使用AsyncTask进行网络操作。

请查看Process & threads in Android了解详情。

看看这个 AsyncTask Example了解更多信息。

答案 1 :(得分:1)

像这样做asynctask:

private class RetreiveDataAsynctask extends AsyncTask<String loginUrlString, Void, JSONObject> {

    @Override
    protected Response doInBackground(Void... params) {
        JSONObject obj = getJSONfromURL( loginUrlString);
        return obj;
    }

    @Override
    protected void onPostExecute(JSONObject obj) {
         //Do all ur UI related stuff as this will be executing in ui thread

        super.onPostExecute(result);
    }


}

然后在你的OnCreate

RetreiveDataAsynctask mRetreiveData = new RetreiveDataAsynctask();
        mRetreiveData.execute();

答案 2 :(得分:0)

试试这个:

class Communicator extends AsyncTask<String, String, String> 
    {
        @Override
        protected String doInBackground(String... params) {
            //Here call the method for parsing
        }

        @Override
        protected void onPreExecute() 
        {
            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(String result) 
        {
            super.onPostExecute(result);
        }
    }

//And on callLoginService(View v) you start the AsyncTask
        //if you want to pass some value
        String values[] = { userna, passwo };
        new Communicator().execute(values); 
        //Otherwise
        new Communicator().execute(); 

答案 3 :(得分:0)

使用异步任务从URL获取Json .. 或在方法中添加以下两行

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);