js url在android中不起作用

时间:2014-12-29 07:21:09

标签: javascript android

嗨在我的应用程序中,我正在使用此js文件来获取json响应 xamp->htdoc->node-chat->node_modules->config->request这是文件的路径

http://www.learn2crack.com/2014/11/android-chat-application-using-gcm-mysql.html

在客户端,我正在使用这样的路径

UserFragment.java

public class UserFragment extends Fragment {
ListView list;
ArrayList<HashMap<String, String>> users = new ArrayList<HashMap<String, String>>();
Button refresh,logout;
List<NameValuePair> params;
SharedPreferences prefs;


@Override
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
    View view =inflater.inflate(R.layout.user_fragment, container, false);
    prefs = getActivity().getSharedPreferences("Chat", 0);

    list = (ListView)view.findViewById(R.id.listView);
    refresh = (Button)view.findViewById(R.id.refresh);
    logout = (Button)view.findViewById(R.id.logout);
    logout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new  Logout().execute();

        }
    });
    refresh.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            getFragmentManager().beginTransaction().remove(getFragmentManager().findFragmentById(R.id.content_frame)).commit();
            Fragment reg = new UserFragment();
            FragmentTransaction ft = getFragmentManager().beginTransaction();
            ft.replace(R.id.content_frame, reg);
            ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
            ft.addToBackStack(null);
            ft.commit();

        }
    });
    new Load().execute();

    return view;
}

private class Load extends AsyncTask<String, String, JSONArray> {

    @Override
    protected JSONArray doInBackground(String... args) {
        JSONParser json = new JSONParser();
        params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("mobno", prefs.getString("REG_FROM","")));
        JSONArray jAry = json.getJSONArray("http://10.0.2.2:8080/node-chat/getuser",params);

        return jAry;
    }
    @Override
    protected void onPostExecute(JSONArray json) {
        for(int i = 0; i < json.length(); i++){
            JSONObject c = null;
            try {
                c = json.getJSONObject(i);
                String name = c.getString("name");
                String mobno = c.getString("mobno");
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("name", name);
                map.put("mobno", mobno);
                users.add(map);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
        ListAdapter adapter = new SimpleAdapter(getActivity(), users,
                R.layout.user_list_single,
                new String[] { "name","mobno" }, new int[] {
                R.id.name, R.id.mobno});
        list.setAdapter(adapter);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                Bundle args = new Bundle();
                args.putString("mobno", users.get(position).get("mobno"));
                Intent chat = new Intent(getActivity(), ChatActivity.class);
                chat.putExtra("INFO", args);
                startActivity(chat);
            }
        });
    }
}
private class Logout extends AsyncTask<String, String, JSONObject> {

    @Override
    protected JSONObject doInBackground(String... args) {
        JSONParser json = new JSONParser();
        params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("mobno", prefs.getString("REG_FROM","")));
        JSONObject jObj = json.getJSONFromUrl("http://10.0.2.2:8080/node-chat/logout",params);

        return jObj;
    }
    @Override
    protected void onPostExecute(JSONObject json) {

        String res = null;
        try {
            res = json.getString("response");
            Toast.makeText(getActivity(),res,Toast.LENGTH_SHORT).show();
            if(res.equals("Removed Sucessfully")) {
                Fragment reg = new LoginFragment();
                FragmentTransaction ft = getFragmentManager().beginTransaction();
                ft.replace(R.id.content_frame, reg);
                ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                ft.addToBackStack(null);
                ft.commit();
                SharedPreferences.Editor edit = prefs.edit();
                edit.putString("REG_FROM", "");
                edit.commit();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }



    }
}

运行此应用程序后出现此logcat错误。

logcat的

12-29 01:47:09.198: E/Buffer Error(1982): Error converting result java.lang.NullPointerException: lock == null
12-29 01:47:09.198: E/JSON Parser(1982): Error parsing data org.json.JSONException: End of input at character 0 of 
12-29 01:47:58.818: D/AndroidRuntime(1982): Shutting down VM
12-29 01:47:58.818: W/dalvikvm(1982): threadid=1: thread exiting with uncaught exception (group=0xb2aa5ba8)
12-29 01:47:58.938: E/AndroidRuntime(1982): FATAL EXCEPTION: main
12-29 01:47:58.938: E/AndroidRuntime(1982): Process: com.example.androidchat, PID: 1982
12-29 01:47:58.938: E/AndroidRuntime(1982): java.lang.NullPointerException
12-29 01:47:58.938: E/AndroidRuntime(1982):     at com.example.androidchat.UserFragment$Load.onPostExecute(UserFragment.java:85)
12-29 01:47:58.938: E/AndroidRuntime(1982):     at com.example.androidchat.UserFragment$Load.onPostExecute(UserFragment.java:1)
12-29 01:47:58.938: E/AndroidRuntime(1982):     at android.os.AsyncTask.finish(AsyncTask.java:632)
12-29 01:47:58.938: E/AndroidRuntime(1982):     at android.os.AsyncTask.access$600(AsyncTask.java:177)
12-29 01:47:58.938: E/AndroidRuntime(1982):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
12-29 01:47:58.938: E/AndroidRuntime(1982):     at android.os.Handler.dispatchMessage(Handler.java:102)
12-29 01:47:58.938: E/AndroidRuntime(1982):     at android.os.Looper.loop(Looper.java:136)
12-29 01:47:58.938: E/AndroidRuntime(1982):     at android.app.ActivityThread.main(ActivityThread.java:5017)
12-29 01:47:58.938: E/AndroidRuntime(1982):     at java.lang.reflect.Method.invokeNative(Native Method)
12-29 01:47:58.938: E/AndroidRuntime(1982):     at java.lang.reflect.Method.invoke(Method.java:515)
12-29 01:47:58.938: E/AndroidRuntime(1982):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
12-29 01:47:58.938: E/AndroidRuntime(1982):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
12-29 01:47:58.938: E/AndroidRuntime(1982):     at dalvik.system.NativeStart.main(Native Method)
12-29 01:48:12.648: W/System.err(1982): org.apache.http.conn.HttpHostConnectException: Connection to http://10.0.2.2:8080 refused
12-29 01:48:12.658: W/System.err(1982):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:183)
12-29 01:48:12.668: W/System.err(1982):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
12-29 01:48:12.678: W/System.err(1982):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
12-29 01:48:12.688: W/System.err(1982):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
12-29 01:48:12.698: W/System.err(1982):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
12-29 01:48:12.708: W/System.err(1982):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
12-29 01:48:12.718: W/System.err(1982):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
12-29 01:48:12.728: W/System.err(1982):     at com.example.androidchat.JSONParser.getJSONArray(JSONParser.java:81)
12-29 01:48:12.748: W/System.err(1982):     at com.example.androidchat.UserFragment$Load.doInBackground(UserFragment.java:79)
12-29 01:48:12.758: W/System.err(1982):     at com.example.androidchat.UserFragment$Load.doInBackground(UserFragment.java:1)
12-29 01:48:12.768: W/System.err(1982):     at android.os.AsyncTask$2.call(AsyncTask.java:288)
12-29 01:48:12.778: W/System.err(1982):     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
12-29 01:48:12.778: W/System.err(1982):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
12-29 01:48:12.788: W/System.err(1982):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
12-29 01:48:12.798: W/System.err(1982):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
12-29 01:48:12.808: W/System.err(1982):     at java.lang.Thread.run(Thread.java:841)
12-29 01:48:12.818: W/System.err(1982): Caused by: java.net.ConnectException: failed to connect to /10.0.2.2 (port 8080): connect failed: ETIMEDOUT (Connection timed out)
12-29 01:48:12.848: W/System.err(1982):     at libcore.io.IoBridge.connect(IoBridge.java:114)
12-29 01:48:12.858: W/System.err(1982):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
12-29 01:48:12.868: W/System.err(1982):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
12-29 01:48:12.878: W/System.err(1982):     at java.net.Socket.connect(Socket.java:843)
12-29 01:48:12.888: W/System.err(1982):     at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
12-29 01:48:12.898: W/System.err(1982):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
12-29 01:48:12.908: W/System.err(1982):     ... 15 more
12-29 01:48:12.918: W/System.err(1982): Caused by: libcore.io.ErrnoException: connect failed: ETIMEDOUT (Connection timed out)
12-29 01:48:12.938: W/System.err(1982):     at libcore.io.Posix.connect(Native Method)
12-29 01:48:12.948: W/System.err(1982):     at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:85)
12-29 01:48:12.958: W/System.err(1982):     at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
12-29 01:48:12.968: W/System.err(1982):     at libcore.io.IoBridge.connect(IoBridge.java:112)
12-29 01:48:12.968: W/System.err(1982):     ... 20 more

request.js

var request = require('request');
var mysql = require('mysql');

var connection = mysql.createConnection(
    {
      host     : 'localhost',
      user     : 'root',
      password : '',
      database : 'chat',
    }
);

connection.connect();


exports.login = function(name,mobno,reg_id,callback) {

var data = {

            name    : name,
            mobno :  mobno,
            reg_id   : reg_id


        };
var que = "SELECT * from users WHERE mobno =" + mobno;

 var query = connection.query(que, function(err, rows)
        {
          if(rows.length == 0){
            var query = connection.query("INSERT INTO users set ? ",data, function(err, rows)
        {

          callback({'response':"Sucessfully Registered"});

        });
          }else {

           callback({'response':"User already Registered"});

          }

        });


}


exports.getuser = function(mobno,callback) {



 var query = connection.query("SELECT * from users", function(err, rows)
        {
          if(rows.length == 0){
            callback({'response':"No Users Registered"});
          }else {

          callback(removeUser(rows, mobno));

          }

        });

}


exports.removeuser = function(mobno,callback) {

var que = "DELETE FROM users  WHERE mobno =" + mobno;

var query = connection.query(que, function(err, rows)
        {

             if(!err){

    callback({'response':"Removed Sucessfully"});
  }else{
    callback({'response':"Error"});
  }  
        });
}



exports.send = function(fromn,fromu,to,msg,callback) {

var que = "SELECT * from users WHERE mobno =" + to;

 var query = connection.query(que, function(err, rows)
        {
          if(rows.length == 0){
            callback({'response':"Failure"});

          }else {


    var to_id = rows[0].reg_id;
    var name = rows[0].name;

request(
    { method: 'POST', 
    uri: 'https://android.googleapis.com/gcm/send',
    headers: {
        'Content-Type': 'application/json',
        'Authorization':'xxxxxxx'
    },
    body: JSON.stringify({
  "registration_ids" : [to_id],
  "data" : {
    "msg":msg,
    "fromu":fromu,
    "name":fromn
  },
  "time_to_live": 108
})
    }
  , function (error, response, body) {

      callback({'response':"Success"});
    }
  )
}});

}

function removeUser(arr, val) {
    for(var i=0; i<arr.length; i++) {
        if(arr[i].mobno == val) {
            arr.splice(i, 1);
            return arr;
            break;
        }
    }
}

0 个答案:

没有答案