简体   繁体   中英

Debugging Android App communicating with Servlet on real device

So the scenario is I am trying to debug a simple application on my real device.I am using eclipse to make the application.

Now my application is communicating with a servlet which is on Server and application is running very smoothly in genymotion emulator(not using the emulator provided by eclipse). But when I try to run it in my device it is working perfectly till one activity class,but application is crashing on second activity. So, after so many searches I am posting this question here. Hope I can find out any solution for this.

This is my Second Activity :

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

                    }
             });    }


        }

This is what my Log cat shows when asynctask is satrting after button click:

        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

If you use a real device you need to use the real IP of the server. Keep also in mind to open the required ports for your local network and connect your mobile with your local network via WiFi.

I'm not very familar with the secutity of servlets check also that you can connect to the server with a second computer too. (Depending on your configuration it is possible that you cannot access the server from outside of "localhost")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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