2012-03-14 2 views
0

그래서 백그라운드에서 앱에 대한 네트워크 작업을 처리하는 스레드가 있었지만 IDE가 UI를 업데이트하고 있다고 생각하고있었습니다. t 중지 충돌. AsyncTask로 변경했는데 이제 Index Out of Range 오류가 발생합니다. 애플 리케이션 스레딩 작업을 시작하기 전에는 제대로 작동했지만 느렸다. 내가 방금 스레드에 추가 한 원래 코드를 변경하지 않았습니다. 그래서 나는 원래의 코드가 AsyncTask를 생성하는 코드이거나 적어도 그 코드 여야한다는 것이 문제가 아니라는 것을 알고있다. 내 코드는 오류와 함께 다음과 같습니다AsyncTask를 추가 한 후 인덱스가 범위를 벗어남 오류가 발생했습니다.

홈페이지 자바

package shc_BalloonSat.namespace; 
import android.app.ProgressDialog; 
import android.os.AsyncTask; 

public class runDialog extends AsyncTask<String, Integer, String> 
{ 
Shc_BalloonSat_Activity shc; 
httpAPI api; 
ProgressDialog progressDialog; 

public void onPreExecute() 
{ 
progressDialog = new ProgressDialog(shc); 
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 
progressDialog.show(); 
} 

@Override 
protected String doInBackground(String... params) 
{ 
for (int count = 0; count < 20; count++) 
{ 
    publishProgress(5); 

    try 
    { 
    api.getData(); 
    } 

    catch (Exception e) 
    { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
    } 
} 

progressDialog.dismiss(); 
return null; 
} 

protected void onProgressUpdate(Integer...progress) 
{ 
progressDialog.incrementProgressBy(progress[0]); 
} 

protected void onPostExecute() 
{ 

} 
} 
,691 runDialog.java

package shc_BalloonSat.namespace; 
import java.text.DecimalFormat; 
import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 
import android.app.Activity; 
import android.app.AlertDialog; 
import android.content.Context; 
import android.content.DialogInterface; 
import android.content.SharedPreferences; 
import android.content.SharedPreferences.Editor; 
import android.net.ConnectivityManager; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.Menu; 
import android.view.MenuInflater; 
import android.view.MenuItem; 
import android.view.SubMenu; 
import android.widget.TextView; 
import android.widget.Toast; 

public class Shc_BalloonSat_Activity extends Activity 
{ 
int historyCountFromUser; 
httpAPI api; 
mapAPI map; 
runDialog dialog; 
DecimalFormat df = new DecimalFormat("##.#####"); 
DecimalFormat decimalf = new DecimalFormat("##.######"); 
AlertDialog alert; 
SharedPreferences pref; 
Editor prefEditor; 
String lastpacketsPHP; 


// User to determine how many packet the user would like to see. 
int userDefinedCount = 5; 

/* 
* Called when the activity is first created. 
*/ 

@Override 
public void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    loadApp(); 
} 

public boolean isNetworkConnected(Context context) 
{ 
    ConnectivityManager connectionManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 
    if (connectionManager.getActiveNetworkInfo() != null && connectionManager.getActiveNetworkInfo().isAvailable() && connectionManager.getActiveNetworkInfo().isConnected()) 
    { 
     return true; 
    } 

    else 
    { 
     return false; 
    } 
} 

public void showAlert() 
{ 
    alert.setTitle("Sorry!"); 
    alert.setMessage("Please connect to the internet to access the full functionality of this app."); 
    alert.setButton("OK", new DialogInterface.OnClickListener() 
    { 
     public void onClick(DialogInterface dialog, int which) 
     { 

     } 
    }); 
    alert.show(); 
} 

/* public void onResume() 
{ 
    super.onResume(); 
    loadApp(); 
} 

public void onRestart() 
{ 
    super.onRestart(); 
    loadApp(); 
}*/ 

public void loadApp() 
{ 
    setContentView(shc_BalloonSat.namespace.R.layout.main); 
    alert = new AlertDialog.Builder(this).create(); 
    String returned = ""; 
    lastpacketsPHP = ""; 
    pref = getSharedPreferences("shared_prefs", 0); 
    prefEditor = pref.edit(); 
    prefEditor.putString(lastpacketsPHP, "/* PHP file URL goes here */"); 
    prefEditor.commit(); 

    // These next two lines are used to test the PHP files on the SHC server by determining if PHP is set up correctly. 
    //prefEditor.putString(lastpacketsPHP, "/* PHP file URL goes here */"); 
    //prefEditor.commit(); 

    if (!isNetworkConnected(this)) 
    { 
    showAlert(); 
    } 

    else 
    { 
    api = new httpAPI(this); 
     map = new mapAPI(this); 
     dialog = new runDialog(); 

     try 
     { 
      returned = api.getData(); 
     } 

    catch (Exception e) 
    { 
     Toast.makeText(this, "Error: Unable to receive data at this time.", Toast.LENGTH_SHORT).show(); 
    } 

     TextView infoTV = (TextView)this.findViewById(shc_BalloonSat.namespace.R.id.info); 
    infoTV.setText(returned); 
    assignInfoToInfoTextView(); 
    assignInfoToHistoryTextView(); 
    } 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) 
{ 
    MenuInflater inflater = getMenuInflater(); 
    inflater.inflate(shc_BalloonSat.namespace.R.menu.mainmenu, menu); 

    SubMenu submenu = menu.addSubMenu(0, Menu.FIRST, Menu.NONE, "Preferences"); 
    submenu.add(0, 5, Menu.NONE, "Get Last 5 Packets"); 
    submenu.add(0, 10, Menu.NONE, "Get Last 10 Packets"); 
    submenu.add(0, 20, Menu.NONE, "Get Last 20 Packets"); 
    inflater.inflate(shc_BalloonSat.namespace.R.menu.mainmenu, submenu); 

    return true; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) 
{ 
    // Handle item selection 
    switch (item.getItemId()) 
    { 
     case shc_BalloonSat.namespace.R.id.viewKML: 
      viewKML(); 
      return true; 
     case 5: 
      viewLast5Packets(); 
      return true; 
     case 10: 
      viewLast10Packets(); 
      return true; 
     case 20: 
      viewLast20Packets(); 
      return true; 
     default: 
      return super.onOptionsItemSelected(item); 
    } 
} 

public void assignInfoToInfoTextView() 
{ 
    TextView infoTV = (TextView)this.findViewById(shc_BalloonSat.namespace.R.id.info); 

    try 
    { 
     String result = api.result.substring(1, api.result.length()-2); 
     JSONObject json_data = new JSONObject(result); 

    double altitudeData = json_data.getDouble("altitude"); 
    double altitudeInFeet = altitudeData * 3.281; 
    String infoText = "Last Known Altitude: " + df.format(altitudeInFeet) + " ft\n"; 

    Double speedData = json_data.optDouble("speed"); 

    if (speedData.isNaN()) 
    { 
     speedData = 0.00; 
    } 

    Double direction = json_data.optDouble("heading"); 
    String directionUnits = " degrees from N"; 
     String directionText = ""; 

     if (direction == 0) 
     { 
      directionText = ", N"; 
     } 
     else if (direction > 0 && direction < 45) 
     { 
      directionText = ", N NE"; 
     } 

     else if (direction == 45) 
     { 
      directionText = ", NE"; 
     } 

     else if (direction > 45 && direction < 90) 
     { 
      directionText = ", E NE"; 
     } 

     else if (direction == 90) 
     { 
      directionText = ", E"; 
     } 

     else if (direction > 90 && direction < 135) 
     { 
      directionText = ", E SE"; 
     } 

     else if (direction == 135) 
     { 
      directionText = ", SE"; 
     } 

     else if (direction > 135 && direction < 180) 
     { 
      directionText = ", S SE"; 
     } 

     else if (direction == 180) 
     { 
      directionText = ", S"; 
     } 

     else if (direction > 180 && direction < 225) 
     { 
      directionText = ", S SW"; 
     } 

     else if (direction == 225) 
     { 
      directionText = ", SW"; 
     } 

     else if (direction > 225 && direction < 270) 
     { 
      directionText = ", W SW"; 
     } 

     else if (direction == 270) 
     { 
      directionText = ", W"; 
     } 

     else if (direction > 270 && direction < 315) 
     { 
      directionText = ", W NW"; 
     } 

     else if (direction == 315) 
     { 
      directionText = ", NW"; 
     } 

     else if (direction > 315 && direction < 360) 
     { 
      directionText = ", N NW"; 
     } 

     else if (direction.isNaN()) 
     { 
     directionText = " Invalid direction"; 
     } 

     else 
      { 

      } 

     infoText += "Last Known Velocity: " + df.format(speedData) + " m/s " + direction + directionUnits + directionText + "\n"; 

    double recentLatitudeData = json_data.getDouble("latitude"); 
    infoText += "Last Known Latitude: " + df.format(recentLatitudeData) + "\n"; 

    double recentLongitudeData = json_data.getDouble("longitude"); 
    infoText += "Last Known Longtitude: " + df.format(recentLongitudeData) + "\n"; 

    infoTV.setText(infoText); 
    } 

    catch (JSONException e) 
    { 
     // TODO Auto-generated catch block 
     Log.e("<tag>", e.getMessage()); 
     Toast.makeText(this,"Error in (Last Known) method!",Toast.LENGTH_SHORT).show(); 
    } 
    catch (Exception e) 
    { 
     Log.e("<tag>", e.getMessage()); 
     Toast.makeText(this,"Error in (Last Known) method!",Toast.LENGTH_SHORT).show(); 
    } 
} 

public void assignInfoToHistoryTextView() 
{ 

    try 
    { 
     JSONArray jArray = new JSONArray(api.result); 
     TextView historyTV = (TextView)this.findViewById(shc_BalloonSat.namespace.R.id.history); 

     for (int count = 1; count < userDefinedCount; count++) 
     { 
       JSONObject json_data = jArray.getJSONObject(count); 

       double altitudeData = json_data.getDouble("altitude"); 
       double altitudeInFeet = altitudeData * 3.281; 
       String historyText = "Altitude: " + decimalf.format(altitudeInFeet) + " ft\n"; 

       Double speedData = json_data.optDouble("speed"); 

       if (speedData.isNaN()) 
       { 
        speedData = 0.00; 
       } 

        Double direction = json_data.optDouble("heading"); 
        String directionUnits = " degrees from N"; 
      String directionText = ""; 

      if (direction == 0) 
      { 
       directionText = ", N"; 
      } 
      else if (direction > 0 && direction < 45) 
      { 
       directionText = ", N NE"; 
      } 

      else if (direction == 45) 
      { 
       directionText = ", NE"; 
      } 

      else if (direction > 45 && direction < 90) 
      { 
       directionText = ", E NE"; 
      } 

      else if (direction == 90) 
      { 
       directionText = ", E"; 
      } 

      else if (direction > 90 && direction < 135) 
      { 
       directionText = ", E SE"; 
      } 

      else if (direction == 135) 
      { 
       directionText = ", SE"; 
      } 

      else if (direction > 135 && direction < 180) 
      { 
       directionText = ", S SE"; 
      } 

      else if (direction == 180) 
      { 
       directionText = ", S"; 
      } 

      else if (direction > 180 && direction < 225) 
      { 
       directionText = ", S SW"; 
      } 

      else if (direction == 225) 
      { 
       directionText = ", SW"; 
      } 

      else if (direction > 225 && direction < 270) 
      { 
       directionText = ", W SW"; 
      } 

      else if (direction == 270) 
      { 
       directionText = ", W"; 
      } 

      else if (direction > 270 && direction < 315) 
      { 
       directionText = ", W NW"; 
      } 

      else if (direction == 315) 
      { 
       directionText = ", NW"; 
      } 

      else if (direction > 315 && direction < 360) 
      { 
       directionText = ", N NW"; 
      } 

      else if (direction.isNaN()) 
      { 
       directionText = " Invalid direction"; 
      } 

      else 
      { 

      } 

      if (direction.isNaN()) 
      { 
       historyText += "Velocity: " + df.format(speedData) + " m/s " + directionText + "\n"; 
      } 

      else 
      { 
       historyText += "Velocity: " + df.format(speedData) + " m/s,\n" + direction + directionUnits + directionText + "\n"; 
      } 

       double latitudeData = json_data.getDouble("latitude"); 
       historyText += "Latitude: " + df.format(latitudeData) + "\n"; 

       double longitudeData = json_data.getDouble("longitude"); 
       historyText += "Longtitude: " + df.format(longitudeData) + "\n\n"; 

       historyTV.setText(historyText); 
     } 
    } 

    catch (JSONException e) 
    { 
     // TODO Auto-generated catch block 
     Log.e("log_tag", "Error parsing data: " + e.toString()); 
    } 
    catch(Exception e) 
    { 
     Log.e("log_tag", "Error parsing data: " + e.toString()); 
    } 

} 

void viewLast5Packets() 
{ 
    if (!isNetworkConnected(this)) 
    { 
     showAlert(); 
    } 

    else 
    { 
     userDefinedCount = 5; 
     prefEditor.putString(lastpacketsPHP, "http://space.uah.edu/balloonsat_app/get_last_5_BS_packets.php"); 
     prefEditor.commit(); 
     assignInfoToInfoTextView(); 
     assignInfoToHistoryTextView(); 
    } 
} 

void viewLast10Packets() 
{ 
    if (!isNetworkConnected(this)) 
    { 
     showAlert(); 
    } 

    else 
    { 
     userDefinedCount = 10; 
     prefEditor.putString(lastpacketsPHP, "http://space.uah.edu/balloonsat_app/get_last_10_BS_packets.php"); 
     prefEditor.commit(); 
     assignInfoToInfoTextView(); 
     assignInfoToHistoryTextView(); 
    } 
} 

void viewLast20Packets() 
{ 
    if (!isNetworkConnected(this)) 
    { 
     showAlert(); 
    } 

    else 
    { 
     userDefinedCount = 20; 
     prefEditor.putString(lastpacketsPHP, "http://space.uah.edu/balloonsat_app/get_last_20_BS_packets.php"); 
     prefEditor.commit(); 
     assignInfoToInfoTextView(); 
     assignInfoToHistoryTextView(); 
    } 
} 

public void viewKML() 
{ 
    if (!isNetworkConnected(this)) 
    { 
     showAlert(); 
    } 

    else 
    { 
     map.openKML(); 
    } 
} 
} 

httpAPI.java

package shc_BalloonSat.namespace; 

import java.io.BufferedReader; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.util.ArrayList; 
import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.NameValuePair; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.impl.client.DefaultHttpClient; 
import android.util.Log; 

public class httpAPI 
{ 
Shc_BalloonSat_Activity shc; 
HttpClient client; 
ArrayList<NameValuePair> nameValuePairs; 
HttpResponse response; 
HttpEntity entity; 
InputStream is; 
String result = ""; 
HttpPost httppost; 

public httpAPI(Shc_BalloonSat_Activity aContext) 
{ 
     shc = aContext; 
} 

public String getData() throws Exception 
{ 
    try 
    { 
    client = new DefaultHttpClient(); 
    nameValuePairs = new ArrayList<NameValuePair>(); 
    httppost = new HttpPost(shc.pref.getString(shc.lastpacketsPHP, shc.lastpacketsPHP.toString())); 
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
    response = client.execute(httppost); 
    entity = response.getEntity(); 
    is = entity.getContent(); 
    } 

    catch (Exception e) 
    { 
    Log.e("log_tag", "Error in HTTP connection: " + e.toString()); 
    } 

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

     is.close(); 

     result = sb.toString(); 
    } 

    catch(Exception e) 
    { 
    Log.e("log_tag", "Error converting result: " + e.toString()); 
    } 

    return result; 
} 
} 

파일

오류 :

org.json.JSONException: Index 5 out of range [0..5) 

이 오류는 URL에서 데이터를 가져 오려고 시도 할 때마다 얻을. 또한 APK 파일을 실제로보고있는 사람들에게 이메일로 보낼 수 있습니다. 나는 또한 이것의 원인이 내 ProgressDialog가 나타나지 않을 수도 있다고 믿을만한 이유가 있습니다. 왜 내가이 오류가 발생할 수있는 아이디어?

+0

기본 활동에서 runDialog를 호출하지 못했습니다. 또한 http://developer.android.com/guide/topics/fundamentals/activities.html#Lifecycle을 읽으십시오. loadApp()가 두 번 호출되는 것처럼 보입니다. 당신이 아마 원하지 않는 대부분의 시간. – mkso

+0

나는 두 번 이상 호출되는 loadApp()에 대해 정확하다고 생각합니다. 내가 방금 읽었던 것에서 : http://stackoverflow.com/questions/8515936/android-activity-life-cycle-difference-between-onpause-and-onstop 내가 그 스레드에서 이해했던 것에서 그것은 한 번 이상 호출 될 것이다. . 또한 다른 클래스처럼 다른 else 문에서 runDialog를 호출했습니다. 현재와 ​​일치하도록 코드를 업데이트했습니다. – tylerbhughes

답변

-2

나는 ProgressDialog를 올바르게 호출하지 않고 액티비티를 전달하고 있고, AsyncTask를 잘못 설정했다. 내가 나를 위해 디버그를 정렬 할 시간이있는 누군가를 찾았습니다.

+0

비슷한 문제가 있습니다. 코드에서 정확한 변경 사항을 알 수 있습니까? – gauravsapiens