0

我是 Android 编程新手。我浏览了 Google 提供的大部分 Android 开发者文档。这是我的问题:

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

登录活动.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 

由于 NetworkOnMainThreadException 异常(在 stackoverflow 的帮助下),我也检查了 AsyncTask。但我不知道从哪里开始以及如何在我的 LoginActivity.java 类中使用 Async 类。请帮忙。提前感谢您。

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

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

@gabe:谢谢你早日回复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);

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

4

4 回答 4

1

错误

Error in http connection android.os.NetworkOnMainThreadException

表示您正在主线程上进行工作,但您应该在单独的线程中进行工作,因为您的网络操作会阻塞 User Interface

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

查看Android 中的进程和线程以获取更多信息。

查看此 AsyncTask 示例以获取更多信息。

于 2013-02-13T11:30:08.047 回答
1

像这样制作异步任务:

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();
于 2013-02-13T11:35:54.697 回答
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(); 
于 2013-02-13T11:36:10.750 回答
0

使用 Async Task 从 url 获取 Json .. 或在您的方法中添加以下两行

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy); 
于 2013-02-13T11:37:33.547 回答