0

MainActivity.java

AutoCompleteTextView location, destination;
public Places place1, place2;
Button calculate;
TextView result_a, result_b;
String result_main;
//default values for taxi fare
int basePrice = 10;
double priceMeter = 5.80;
double fare;
int parseFare;
int roundedValue;
String textvalue;
String actual_distance;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    location=(AutoCompleteTextView)findViewById(R.id.locale);
    location.setAdapter(new PlacesAutoCompleteAdapter(this, R.layout.list_item));
    location.setOnItemClickListener(new OnItemClickListener()
    {

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
            // TODO Auto-generated method stub
            place1 = (Places) adapterView.getItemAtPosition(position);
            location.setText(place1.description);
            //location.clearFocus();
            Log.d("AutoCompleteTask", location.getText().toString());
                }
    });

    destination = (AutoCompleteTextView)findViewById(R.id.destination);
    destination.setAdapter(new PlacesAutoCompleteAdapter(this, R.layout.list_item));
    destination.setOnItemClickListener(new OnItemClickListener() 
    {

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                // TODO Auto-generated method stub
            place2 = (Places) adapterView.getItemAtPosition(position);
            destination.setText(place2.description);
            //destination.clearFocus();
            Log.d("AutoCompleteTask2", destination.getText().toString());
                }
    });



    calculate = (Button)findViewById(R.id.calculate);

    calculate.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
        new ReadDistanceJSONFeedTask().execute("http://maps.googleapis.com/maps/api/distancematrix/json?origins="+location.getText().toString()+"&destinations="+destination.getText().toString()+"&sensor=false&units=metric&mode=driving");
        //result_a.setText("ROUTE A "+result_main +"\n"+ "The estimated fare is Rs."+textvalue);
        }
    });
}

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


private class ReadDistanceJSONFeedTask extends AsyncTask<String, Void, String>
{       
        @Override
        protected String doInBackground(String... urls) {
            // TODO Auto-generated method stub
            return readJSONFeed(urls[0]);
        }

        @Override
        protected void onPostExecute(String result)
        {
            try
            {   //Accessing the JSON Results
                JSONObject jsonObject = new JSONObject(result);

                JSONArray rows = jsonObject.getJSONArray("rows");
                Log.i("json", rows.toString());

                JSONObject obj = rows.getJSONObject(0);

                JSONArray elements = obj.getJSONArray("elements");

                JSONObject ini_dis = elements.getJSONObject(0);

                JSONObject distance = ini_dis.getJSONObject("distance");
                Log.i("json", distance.toString());

                //Distance to send
                actual_distance = distance.getString("text");

                //Calculation part
                String solve = distance.getString("value");
                int parseFare = Integer.parseInt(solve);
                fare = basePrice + ((parseFare/200)*priceMeter);
                roundedValue = (int)Math.round(fare);

                //another activity
                Intent i = new Intent(MainActivity.this,ResultsDisplay.class);
                i.putExtra("Display",actual_distance);
                i.putExtra("Display_b",textvalue);
                startActivity(i);

            }
            catch(Exception e)
            {
                Log.d("ReadDistanceJSONFeedTask", e.getLocalizedMessage());
            }
        }

            public String readJSONFeed(String URL){
            //Initial steps to getting the JSON Result
            StringBuilder stringBuilder = new StringBuilder();
            HttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(URL);
            try
            {
                HttpResponse response = httpClient.execute(httpGet);
                StatusLine statusLine = response.getStatusLine();
                int statusCode = statusLine.getStatusCode();
                //statusCodes at 200 are OK_Statuses
                if(statusCode==200)
                {
                    HttpEntity entity = response.getEntity();
                    InputStream inputStream = entity.getContent();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                    String line;
                    while((line=reader.readLine())!=null)
                    {
                        stringBuilder.append(line);

                    }
                    inputStream.close();
                }
                else
                {
                    Log.d("readJSONFeed","Failed to download file");
                }
            }
            catch(Exception e)
            {
                Log.d("readJSONFeed", e.getLocalizedMessage());
            }
                return stringBuilder.toString();
        }

}

我正在创建一个应用程序,它接受用户输入的位置目的地,并返回路径之间的距离以及估计的出租车费用。在这个程序中还有一个利用Google-PlacesAPI 的自动完成文本视图功能。这个应用程序使用Direction-Matrix-API我目前遇到的问题AsyncTask...... logcat 在“doInBackGround()”方法中执行时产生错误......请帮助。

LogCat 错误

03-27 09:29:03.785: I/Choreographer(3468): 跳过 123 帧!应用程序可能在其主线程上做了太多工作。03-27 09:29:05.485: W/dalvikvm(3468): threadid=12: 线程退出未捕获异常 (group=0x40a71930) 03-27 09:29:05.525: E/AndroidRuntime(3468): 致命异常: AsyncTask #2 03-27 09:29:05.525:E / AndroidRuntime(3468):java.lang.RuntimeException:执行doInBackground()03-27 09:29:05.525时发生错误:E / AndroidRuntime(3468):在android .os.AsyncTask$3.done(AsyncTask.java:299) 03-27 09:29:05.525: E/AndroidRuntime(3468): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352) 03-27 09:29:05.525: E/AndroidRuntime(3468): 在 java.util.concurrent.FutureTask.setException(FutureTask.java:219) 03-27 09:29:05.525: E/AndroidRuntime(3468): 在 java.util . http://maps.googleapis.com/maps/api/distancematrix/json?origins=Lagankhel Rd, Patan, Central Region, Nepal&destinations=Thamel, Kathmandu, Central Region, Nepal&sensor=false&units=metric&mode=driving 03-27 09:29:05.525: E/AndroidRuntime(3468): at java.net.URI.create(URI. java:727) 03-27 09:29:05.525: E/AndroidRuntime(3468): at org.apache.http.client.methods.HttpGet.(HttpGet.java:75) 03-27 09:29:05.525: E /AndroidRuntime(3468): 在 com.example.calculator_taxi_fare.MainActivity$ReadDistanceJSONFeedTask.readJSONFeed(MainActivity.java:159) 03-27 09:29:05.525: E/AndroidRuntime(3468): 在 com.example.calculator_taxi_fare.MainActivity$ ReadDistanceJSONFeedTask.doInBackground(MainActivity.java:111) 03-27 09:29:05.525: E/AndroidRuntime(3468): at com.example.calculator_taxi_fare.MainActivity$ReadDistanceJSONFeedTask.doInBackground(MainActivity.java:1) 03-27 09: 29:05.525:E/AndroidRuntime(3468): 在 android.os.AsyncTask$2.call(AsyncTask.java:287) 03-27 09:29:05.525: E/AndroidRuntime(3468): 在 java.util.concurrent.FutureTask.run( FutureTask.java:234) 03-27 09:29:05.525: E/AndroidRuntime(3468): ... 4 更多

4

1 回答 1

1

在这里

@Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
        new ReadDistanceJSONFeedTask().execute("your url");
        ....
        startActivity(i); //<<<<<

}

您正在执行ReadDistanceJSONFeedTaskAsyncTask 后开始下一个 Activity。因为 AsyncTask 在单独的线程中执行并且控制到达下一行而不等待 AsyncTask 结果。

移动 Activity 开始部分 onPostExecute,在执行完成后在 UI 线程上doInBackground 执行:

@Override
        protected void onPostExecute(String result)
        {
           ///....your code here..
           // start next Activity here..
           Intent i = new Intent(MainActivity.this,ResultsDisplay.class);
           i.putExtra("Display",actual_distance);
           i.putExtra("Display_b",textvalue);
           startActivity(i);
        }

编辑: 您还需要URLEncoder.encode在为 HttpGet 发送参数之前使用

String strparams="origins="+location.getText().toString()+"&
                       destinations="+destination.getText().toString()+
                       "&sensor=false&units=metric&mode=driving";
String encodedurl = URLEncoder.encode(strparams,"UTF-8");
new ReadDistanceJSONFeedTask().execute("http://maps.googleapis.com/maps
                                        /api/distancematrix/json?"+encodedurl);
于 2013-03-29T06:07:41.050 回答