繁体   English   中英

在真实设备上调试与Servlet通信的Android应用

[英]Debugging Android App communicating with Servlet on real device

所以场景是我试图在我的真实设备上调试一个简单的应用程序,我正在使用eclipse制作该应用程序。

现在,我的应用程序正在与服务器上的servlet通信,并且该应用程序在genymotion模拟器中运行得非常顺利(不使用eclipse提供的模拟器)。 但是,当我尝试在设备中运行该程序时,它可以正常运行,直到一个活动类,但应用程序在第二个活动中崩溃。 因此,经过如此多的搜索,我在这里发布了这个问题。 希望我能找到任何解决方案。

这是我的第二项活动

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.success);

        Intent objIntent = getIntent();
        s2 = objIntent.getStringExtra("repname");


        findViewsById();

        submit.setOnClickListener(this);


    }
    private void findViewsById() {


        submit = (Button) findViewById(R.id.submit);
        headerText = (TextView) findViewById(R.id.tv1);
        headerText.setVisibility(View.INVISIBLE);

        submit2 = (Button) findViewById(R.id.secondSubmit);
        submit2.setVisibility(View.INVISIBLE);

         t1= (TextView) findViewById(R.id.tvexample1);
         t2= (TextView) findViewById(R.id.tvexample2);




        submit2.setOnClickListener(new OnClickListener() {
            public void onClick(View v)
            {
                //DO SOMETHING! {RUN SOME FUNCTION ... DO CHECKS... ETC}

                lviewAdapter.clear();
                lviewAdapter.notifyDataSetChanged();
                Calendar cal = Calendar.getInstance();
                System.out.println("what is from calendar"+cal);
              Date currentLocalTime = cal.getTime();
                //System.out.println("what is from CurrentLocalTime"+currentLocalTime);


                DateFormat date = new SimpleDateFormat("yyyy-MM-dd");

                date.setTimeZone(TimeZone.getTimeZone("GMT")); 
                //System.out.println("what is from date"+date);
                String localTime = date.format(currentLocalTime);
             //localTime = "2014-08-26";
                System.out.println("and result is == " + localTime);


                 pb.setVisibility(View.VISIBLE);    


                new MyAsyncTask().execute(localTime,s2);



            } 
        });


        pb=(ProgressBar)findViewById(R.id.progressBar1);
        pb.setVisibility(View.GONE);


      c=this;

    }
        public void onClick(View view) {
            Log.d("1:", "in the onclick");




             Calendar cal = Calendar.getInstance();
             System.out.println("what is from calendar"+cal);

              Date currentLocalTime = cal.getTime();
              //System.out.println("what is from CurrentLocalTime"+currentLocalTime);


              DateFormat date = new SimpleDateFormat("yyyy-MM-dd");

              date.setTimeZone(TimeZone.getTimeZone("GMT")); 
              //System.out.println("what is from date"+date);
              String localTime = date.format(currentLocalTime);
           //localTime = "2014-08-26";
              System.out.println("and result is == " + localTime);





                 pb.setVisibility(View.VISIBLE);    


                new MyAsyncTask().execute(localTime,s2);


    }
//        @Override
//        public void onBackPressed() {
//           Log.d("CDA", "onBackPressed Called");
//           Intent setIntent = new Intent(Intent.ACTION_MAIN);
//           setIntent.addCategory(Intent.CATEGORY_HOME);
//           setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//           startActivity(setIntent);
//        }


    private class MyAsyncTask extends AsyncTask<String, Integer, String>{


        @Override
        protected String doInBackground(String... params) {
            // TODO Auto-generated method stub
            Log.d("tag1","in do in ");
            String s=postData(params);
            Log.d("tag2","in do in SSS ");
            //Printing this 5 th
            Log.d("what is s",s);

            return s;
        }





        protected void onPostExecute(String result){
            Log.d("on post ","on post execute");
            pb.setVisibility(View.GONE);

            Toast.makeText(getApplicationContext(),"Appointment Displayed", Toast.LENGTH_SHORT).show();

            //Log.d("tag",result);


                init(result); 
                submit.setVisibility(View.GONE);
                headerText.setVisibility(View.VISIBLE);
                submit2.setVisibility(View.VISIBLE);
          }


                }

        protected void onProgressUpdate(Integer... progress){
            pb.setProgress(progress[0]);
        }


        public String postData(String valueIWantToSend[]) {

             String origresponseText="";
            try {
                // Add your data
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("CurrentDate",valueIWantToSend[0]));
                nameValuePairs.add(new BasicNameValuePair("repname", valueIWantToSend[1]));
               System.out.println("CurrentDate"+valueIWantToSend[0]);
               System.out.println("username"+valueIWantToSend[1]);
                exampleString1= valueIWantToSend[0];
                exampleString2= valueIWantToSend[1];
                HttpClient httpclient = new DefaultHttpClient();
                HttpParams params = httpclient.getParams();


                HttpConnectionParams.setConnectionTimeout(httpclient.getParams(),10000000);
                 //httppost = new HttpPost("http://192.168.56.1:8080/First/Hello");
                 httppost = new HttpPost("http://203.199.134.131:8080/First/Hello");

                 httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
         /* execute */


                HttpResponse response = httpclient.execute(httppost);

                System.out.println("response from servlet"+response.toString());

                 origresponseText=readContent(response);


Log.d("response", origresponseText);
            } 
      catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
            } 
      catch (IOException e) {
                // TODO Auto-generated catch block
            }

            //removing unwated "" and other special symbols from response
          String responseText = origresponseText.substring(1,origresponseText.length() -2 );

          Log.d("Response tag", responseText);


          return responseText;
        }


  //  }
    String readContent(HttpResponse response)
    {

        String text = "";
        InputStream in =null;

        try {
            in = response.getEntity().getContent();

            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                //Log.d("", line);
                sb.append(line + "\n");
                //Printing this first
//                  Log.d("", line);
//                  Log.e("TAGpppp", ">>>>>PRINTING<<<<<");
//                  Log.e("TAGiiii", in.toString());

                }
                text = sb.toString();

                Log.d("TEXT", text);



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

        } catch (IOException e) {
              e.printStackTrace();
        }
        finally {
            try {

              in.close();
            } catch (Exception ex) {
            }
            }

return text;

    }

    @SuppressWarnings("deprecation")
    public void init(String result) {



        System.out.println(result);

        t1.setText(exampleString1);
        t2.setText(exampleString2);

        String response= result + "}";
        System.out.println(response);
        try {
            JSONObject jsonArray = new JSONObject(response);
            System.out.println("1:"+jsonArray);
            //ArrayList obj1 = new ArrayList();
            JSONArray obj1 = jsonArray.getJSONArray("get");

            System.out.println("1:"+obj1);
            for (int i = 0; i < obj1.length(); i++) {
                System.out.println("Length of array"+obj1.length());


                 JSONObject results = obj1.getJSONObject(i);
                 System.out.println("2:"+results);
                 String pcode= results.getString("ProspCustCode");
                 System.out.println("Prospect code"+pcode);
                 String date= results.getString("FollowUpDate");
                 System.out.println("FollowUpDate"+date);
                 String time= results.getString("FollowUpTime");
                 System.out.println("FollowUpTime"+time);
                 String status= results.getString("Status");
                 System.out.println("Status"+status);
                 String ftype= results.getString("FollowUpType");
                 System.out.println("FollowUpType"+ftype);
                 String ntime= results.getString("NextFollowUpTime");
                 System.out.println("NextFollowUpTime"+ntime);
                 String cname= results.getString("ContactPerson");
                 System.out.println("ContactPerson"+cname);
                 String desig= results.getString("Designation");
                 System.out.println("Designation"+desig);
                 String com= results.getString("Comments");
                 System.out.println("Comments"+com);
                 String spoke= results.getString("SpokenTo");
                 System.out.println("SpokenTo"+spoke);
                 insertdata(pcode,date,time,status,ftype,ntime,cname,desig,com,spoke);

            }


        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
        private void insertdata(String PROSPCUSTCODE, String DATE, String TIME,
                String STATUS, String FOLLOWUPTYPE, String NEXTFOLLOWUPTIME, String NAME,
                String DESIGNATION, String COMMENTS, String SPOKENTO) {
                 HashMap<String, String> queryValues =  new  HashMap<String, String>();
                 queryValues.put("ProspCustCode", PROSPCUSTCODE);
                queryValues.put("Date", DATE);
                queryValues.put("Time", TIME);
                queryValues.put("Status", STATUS);
                queryValues.put("FollowUpType", FOLLOWUPTYPE);
                queryValues.put("NextFollowUpTime", NEXTFOLLOWUPTIME);
                queryValues.put("Name", NAME);
                queryValues.put("Designation", DESIGNATION);
                queryValues.put("Comments", COMMENTS);
                queryValues.put("SpokenTo", SPOKENTO);
                controller.insertDeails(queryValues);
                //this.callHomeActivity(view);









        DBController dbHelper = new DBController(this.getApplicationContext());
        newDB = dbHelper.getWritableDatabase();
        Cursor cursor = newDB.rawQuery("SELECT  * FROM TempFollowUpDetails", null);

        if (cursor != null ) {
            if  (cursor.moveToFirst()) {
                do {
                    System.out.println(cursor.getColumnIndex("ProspCustCode"));
                    //String ProspCustCode = c.getString(c.getColumnIndex("ProsCustCode"));

                     String Date = cursor.getString(cursor.getColumnIndex("Date"));
                    String Time = cursor.getString(cursor.getColumnIndex("Time"));
                    String Status = cursor.getString(cursor.getColumnIndex("Status"));
                    String NextFollowUpTime = cursor.getString(cursor.getColumnIndex("NextFollowUpTime"));
                    Name = cursor.getString(cursor.getColumnIndex("Name"));
                    System.out.println(cursor.getString(cursor.getColumnIndex("Name")));
                    String Designation = cursor.getString(cursor.getColumnIndex("Designation"));
                    String Comments = cursor.getString(cursor.getColumnIndex("Comments"));
                    String SpokenTo = cursor.getString(cursor.getColumnIndex("SpokenTo"));
                    String Id = cursor.getString(cursor.getColumnIndex("Id"));

                    //ProspCustCodeArray.add(ProspCustCode);
                    DateArray.add(Date);
                    TimeArray.add(Time);
                    StatusArray.add(Status);
                    NextFollowUpTimeArray.add(NextFollowUpTime);
                    NameArray.add(Name);



                    DesignationArray.add(Designation);
                    CommentsArray.add(Comments);
                    SpokenToArray.add(SpokenTo);
                    IdArray.add(Id);


                }while (cursor.moveToNext());
            } 
            displaylist(IdArray,NameArray);

        }
        System.out.println("Elements of name array"+NameArray);
        System.out.println("Elements of name array"+DateArray);
        System.out.println("Elements of name array"+TimeArray);
        System.out.println("Elements of name array"+DesignationArray);
        System.out.println("Elements of name array"+CommentsArray);
        System.out.println("Elements of name array"+IdArray);
        //............. For normal listview

}
        private void displaylist(ArrayList<String> idArray2,
                ArrayList<String> nameArray2) {
            // TODO Auto-generated method stub
            listView = (ListView)  findViewById(R.id.listViewAnimals);
            lviewAdapter = new ListCustomAdapter(this, idArray2, nameArray2);
            System.out.println("adapter => "+lviewAdapter.getCount());



            listView.setAdapter(this.lviewAdapter);


            controller.deleteDetails(null);



            //... start appointments details activity to show the details on item click listener

             this.listView.setOnItemClickListener(new OnItemClickListener() {
                 @Override
                    public void onItemClick(AdapterView<?> a, View viewClicked, int position, long id) {
                     TextView tv1 =(TextView)viewClicked.findViewById(R.id.lblListItem);


               Intent intent = new Intent(Success.this, AppointmentDetails.class);

               intent.putExtra("name", tv1.getText().toString());
               startActivity(intent);

                    }
             });    }


        }

这是单击按钮后asynctask处于饱和状态时我的Log cat显示的内容:

        D/1:(15416): in the onclick
     I/System.out(15416): what is from calendarjava.util.GregorianCalendar[time=1409392501700,areFieldsSet=true,lenient=true,zone=Asia/Calcutta,firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2014,MONTH=7,WEEK_OF_YEAR=35,WEEK_OF_MONTH=5,DAY_OF_MONTH=30,DAY_OF_YEAR=242,DAY_OF_WEEK=7,DAY_OF_WEEK_IN_MONTH=5,AM_PM=1,HOUR=3,HOUR_OF_DAY=15,MINUTE=25,SECOND=1,MILLISECOND=700,ZONE_OFFSET=19800000,DST_OFFSET=0]
     I/System.out(15416): and result is == 2014-08-26
     D/tag1(15416): in do in 
     I/System.out(15416): CurrentDate2014-08-26
     I/System.out(15416): usernameaditi
     I/System.out(15416): [socket][1] connection /203.199.134.131:8080;LocalPort=36598(10000000)
     I/System.out(15416): [CDS]connect[/203.199.134.131:8080] tm:10000 D/Posix(15416): [Posix_connect Debug]Process com.example.simplehttpgetservlet :8080 
  I/System.out(22364): [socket][/192.168.2.73:45340] connected

     I/System.out(15416): [CDS]rx timeout:0
     W/System.err(15416): rto value is too small
     I/System.out(15416): >doSendRequest
     I/System.out(15416): <doSendRequest
     I/System.out(15416): response from servletorg.apache.http.message.BasicHttpResponse@423611d8

如果使用真实设备,则需要使用服务器的真实IP。 还请记住打开本地网络所需的端口,并通过WiFi将手机与本地网络连接。

我对servlet的安全性不是很熟悉,您也可以使用第二台计算机连接到服务器。 (根据您的配置,可能无法从“ localhost”外部访问服务器)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM