Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/234.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/windows/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 与远程服务器建立连接时发生logcat错误_Android - Fatal编程技术网

Android 与远程服务器建立连接时发生logcat错误

Android 与远程服务器建立连接时发生logcat错误,android,Android,在试用了提供的一些解决方案后,我能够从服务器检索响应,但仍然无法显示我正在接收的JSON数组,并且应用程序正在崩溃,请帮助我: Logcat错误 07-07 11:12:09.500: E/AndroidRuntime(1829): FATAL EXCEPTION: main 07-07 11:12:09.500: E/AndroidRuntime(1829): java.lang.RuntimeException: Unable to start activity ComponentInfo{

在试用了提供的一些解决方案后,我能够从服务器检索响应,但仍然无法显示我正在接收的JSON数组,并且应用程序正在崩溃,请帮助我:

Logcat错误

07-07 11:12:09.500: E/AndroidRuntime(1829): FATAL EXCEPTION: main
07-07 11:12:09.500: E/AndroidRuntime(1829): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.g2k/com.example.g2k.HotelSearch}: java.lang.NullPointerException: println needs a message
07-07 11:12:09.500: E/AndroidRuntime(1829):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
07-07 11:12:09.500: E/AndroidRuntime(1829):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
07-07 11:12:09.500: E/AndroidRuntime(1829):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
07-07 11:12:09.500: E/AndroidRuntime(1829):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
07-07 11:12:09.500: E/AndroidRuntime(1829):     at android.os.Handler.dispatchMessage(Handler.java:99)
07-07 11:12:09.500: E/AndroidRuntime(1829):     at android.os.Looper.loop(Looper.java:137)
07-07 11:12:09.500: E/AndroidRuntime(1829):     at android.app.ActivityThread.main(ActivityThread.java:5039)
07-07 11:12:09.500: E/AndroidRuntime(1829):     at java.lang.reflect.Method.invokeNative(Native Method)
07-07 11:12:09.500: E/AndroidRuntime(1829):     at java.lang.reflect.Method.invoke(Method.java:511)
07-07 11:12:09.500: E/AndroidRuntime(1829):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
07-07 11:12:09.500: E/AndroidRuntime(1829):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
07-07 11:12:09.500: E/AndroidRuntime(1829):     at dalvik.system.NativeStart.main(Native Method)
07-07 11:12:09.500: E/AndroidRuntime(1829): Caused by: java.lang.NullPointerException: println needs a message
07-07 11:12:09.500: E/AndroidRuntime(1829):     at android.util.Log.println_native(Native Method)
07-07 11:12:09.500: E/AndroidRuntime(1829):     at android.util.Log.v(Log.java:117)
07-07 11:12:09.500: E/AndroidRuntime(1829):     at com.example.g2k.HotelSearch.onCreate(HotelSearch.java:22)
07-07 11:12:09.500: E/AndroidRuntime(1829):     at android.app.Activity.performCreate(Activity.java:5104)
07-07 11:12:09.500: E/AndroidRuntime(1829):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
07-07 11:12:09.500: E/AndroidRuntime(1829):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
07-07 11:12:09.500: E/AndroidRuntime(1829):     ... 11 more
07-07 11:12:14.430: E/Trace(1848): error opening trace file: No such file or directory (2)
源代码:

public class HotelBook extends Activity {
private String resp;

private ProgressDialog pDialog;

// Creating JSON Parser object
JSONParser jParser = new JSONParser();

ArrayList<HashMap<String, String>> hotelsList;
HashMap<String, String> map;
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_HOTEL = "hotels";
private static final String TAG_PID = "hotel_id";
private static final String TAG_NAME = "hotel_name";
private static final String TAG_AREA = "area";
private static final String TAG_RATING = "star_rating";
private static final String TAG_IMAGE = "image";
private static final String TAG_GOVRATE = "govrating";
private static final String TAG_PRICE = "price";

private String city_id = "feedbacktype2";
// products JSONArray
JSONArray hotels = null;

Button sendPostReqButton;
private static final String url = "http://10.0.2.2/android_connect/search_hotel.php";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_hotelbook);
    // Hashmap for ListView
    hotelsList = new ArrayList<HashMap<String, String>>();

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
            .permitAll().build();
    StrictMode.setThreadPolicy(policy);
    sendPostReqButton = (Button) findViewById(R.id.button1);
    addListenerOnButton();
}

public void addListenerOnButton() {

    sendPostReqButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // Get the data
            // Loading products in Background Thread
            new GetHotel().execute();
        }

    });

}

@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_hotelbook, menu);
    return true;
}

class GetHotel extends AsyncTask<String, String, String> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        /*
         * pDialog = new ProgressDialog(HotelbookActivity.this);
         * pDialog.setMessage("Loading hotels. Please wait...");
         * pDialog.setIndeterminate(false); pDialog.setCancelable(false);
         * pDialog.show();
         */
    }

    protected String doInBackground(String... args) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("cityid", city_id));

        // getting JSON string from URL
        JSONObject json = null;
        try {
            json = jParser.makeHttpRequest(url, "GET", params);
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            // Check your log cat for JSON reponse
            Log.e("All hotels: ", e1.toString());
        }

        // Check your log cat for JSON reponse
        Log.d("All hotels: ", json.toString());

        try {
            // Checking for SUCCESS TAG
            int success = 1;
            // json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // products found
                // Getting Array of Products
                hotels = json.getJSONArray(TAG_HOTEL);

                // looping through All Products
                for (int i = 0; i < hotels.length(); i++) {
                    JSONObject c = hotels.getJSONObject(i);

                    // Storing each json item in variable
                    String id = c.getString(TAG_PID);
                    String name = c.getString(TAG_NAME);
                    String area = c.getString(TAG_AREA);
                    String rating = c.getString(TAG_RATING);
                    String image = c.getString(TAG_IMAGE);
                    String price = c.getString(TAG_PRICE);
                    String govrate = c.getString(TAG_GOVRATE);
                    // creating new HashMap
                    map = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    map.put(TAG_PID, id);
                    map.put(TAG_NAME, name);
                    map.put(TAG_AREA, area);
                    map.put(TAG_RATING, rating);
                    map.put(TAG_IMAGE, image);
                    map.put(TAG_PRICE, price);
                    map.put(TAG_GOVRATE, govrate);

                    // adding HashList to ArrayList
                    hotelsList.add(map);
                }

            } else {

            }
        } catch (JSONException e) {
            Log.e("response error", json.toString(), e);
        }

        return null;
    }

    protected void onPostExecute(String file_url) {

        Intent intent = new Intent(HotelBook.this, HotelSearch.class);
        intent.putExtra("map", map);
        startActivity(intent);
    }
}

}
公共类HotelBook扩展活动{
私有字符串resp;
私人对话;
//创建JSON解析器对象
JSONParser jParser=新的JSONParser();
ArrayList酒店列表;
HashMap图;
//JSON节点名称
私有静态最终字符串标记_SUCCESS=“SUCCESS”;
私人静态最终字符串TAG_HOTEL=“hotels”;
私有静态最终字符串TAG_PID=“hotel_id”;
私有静态最终字符串TAG_NAME=“hotel_NAME”;
私有静态最终字符串标记_AREA=“AREA”;
专用静态最终字符串标记\u RATING=“star\u RATING”;
私有静态最终字符串TAG_IMAGE=“IMAGE”;
私有静态最终字符串标记\u GOVRATE=“govrating”;
私有静态最终字符串标记_PRICE=“PRICE”;
私有字符串city_id=“feedbacktype2”;
//产品JSONArray
JSONArray hotels=null;
按钮sendPostReqButton;
私有静态最终字符串url=”http://10.0.2.2/android_connect/search_hotel.php";
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hotelbook);
//ListView的Hashmap
hotelsList=newarraylist();
StrictMode.ThreadPolicy policy=新建StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(策略);
sendPostReqButton=(按钮)findViewById(R.id.button1);
addListenerOnButton();
}
public void addListenerOnButton(){
sendPostReqButton.setOnClickListener(新的OnClickListener(){
@凌驾
公共void onClick(视图arg0){
//获取数据
//在后台线程中加载产品
新建GetHotel().execute();
}
});
}
@凌驾
公共布尔onCreateOptions菜单(菜单){
//为菜单充气;这会将项目添加到操作栏(如果存在)。
getMenuInflater().充气(R.menu.activity\u hotelbook,menu);
返回true;
}
类GetHotel任务{
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
/*
*pDialog=新建进度对话框(HotelbookActivity.this);
*pDialog.setMessage(“正在加载酒店,请稍候…”);
*pDialog.setUndeterminate(false);pDialog.setCancelable(false);
*pDialog.show();
*/
}
受保护的字符串doInBackground(字符串…args){
//建筑参数
List params=new ArrayList();
参数add(新的BasicNameValuePair(“城市id”,城市id));
//从URL获取JSON字符串
JSONObject json=null;
试一试{
json=jParser.makeHttpRequest(url,“GET”,params);
}捕获(IOE1异常){
//TODO自动生成的捕捉块
//检查日志cat中的JSON响应
Log.e(“所有酒店:,e1.toString());
}
//检查日志cat中的JSON响应
Log.d(“所有酒店:,json.toString());
试一试{
//检查成功标签
int成功=1;
//getInt(TAG_SUCCESS);
如果(成功==1){
//发现的产品
//获取一系列产品
hotels=json.getJSONArray(TAG_HOTEL);
//在所有产品中循环
对于(int i=0;ivalue
地图放置(标签PID,id);
地图放置(标签名称、名称);
地图放置(TAG_区域,区域);
地图放置(标签、等级、等级);
地图放置(标签图片,图片);
地图出售(标签价格、价格);
地图放置(标记为GOVRATE,GOVRATE);
//将哈希列表添加到ArrayList
添加(地图);
}
}否则{
}
}捕获(JSONException e){
Log.e(“响应错误”,json.toString(),e);
}
返回null;
}
受保护的void onPostExecute(字符串文件\u url){
意向意向=新意向(HotelBook.this、HotelSearch.class);
意向。额外(“地图”,地图);
星触觉(意向);
}
}
}
JSONParser类:

public class JSONParser {

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

// constructor
public JSONParser() {

}

// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
        List<NameValuePair> params) throws IOException {

    // 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");
        }

        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    } finally {
        is.close();
    }

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

}

}
公共类JSONParser{
InputStream=null;
JSONObject jObj=null;
静态字符串json=“”;
//建造师
公共JSONParser(){
}
//函数从url获取json
//通过使用HTTP POST或GET方法
公共JSONObject makeHttpRequest(字符串url、字符串方法、,
列表参数)引发IOException{
//发出HTTP请求
试一试{
//检查请求方法
如果(方法==“POST”){
//请求方法为POST
//defaultHttpClient
DefaultHttpClient httpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(url);
setEntity(新的UrlEncodedFormEntity(参数));
HttpResponse HttpResponse=httpClient.execute(httpPost);
HttpEntity HttpEntity=httpResponse.getEntity();
is=httpEntity.getContent();
}else if(方法==“GET”){
//请求方法是GET
Caused by: java.lang.NullPointerException
07-05 08:36:07.533: E/AndroidRuntime(1073): at
        com.example.go2kashmir.HotelbookActivity$GetHotel
        .doInBackground(HotelbookActivity.java:154)
Log.d("All hotels: ", json.toString());
All hotels: null
Log.d("MyActivity", "Object of interest is " + objectOfInterest);