Проблема в том, что is
был объявлен внутри первого блока try, что ограничивает его видимость для этого блока. Попробуйте это
// move is declaration before the try-catch
InputStream is = null;
try{
....
// just use it here
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
// it will still be available here.
Это будет работать, потому что будет объявлено вне блока try-Кроме. Не забудьте добавить проверку ошибок, по крайней мере, if (is != null)
, где вы используете is
РЕДАКТИРОВАТЬ - Проверка на ошибки, что я имею в виду: не допускайте, чтобы ошибки доходили до пользователя необработанными, это было неопрятно, сбивало с толку, и суть в том, что они купят вашу конкуренцию. Везде, где это может пойти не так, вы должны сделать что-то, чтобы защитить пользователя, как это
if (is != null) {
// wrapped in if because this code assumes is exists
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();
} else {
// do whatever you have to do to signal to the user that something went wrong.
}
EDIT2: ваш (is! = Null) чек был в очень странном месте. Переместил его в лучшее место, предложенное в моем первоначальном ответе, см. Ниже.
И последнее предложение: понятия не имеете, какой редактор вы используете, но отступы были ужасной неразберихой, код трудно читать без разумного отступа.
public class PS extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final EditText et_Text = (EditText) findViewById(R.id.et_Text);
//add new KeyListener Callback (to record key input)
et_Text.setOnKeyListener(new OnKeyListener() {
//function to invoke when a key is pressed
public boolean onKey(View v, int keyCode, KeyEvent event) {
//check if there is
if (event.getAction() == KeyEvent.ACTION_DOWN) {
//check if the right key was pressed
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
InputStream is = null;
String result = "";
//the name data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name", et_Text.getText().toString()));
//http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://******/sampleDB/testSend.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// At this point is should be set, if it isn't, tell user what went wrong
if (is != null) {
//convert response to string
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());
}
//parse json data
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag", "PersonID: " + json_data.getInt("PersonID")
+ ", FirstName: " + json_data.getString("FirstName")
+ ", LastName: " + json_data.getString("LastName")
+ ", Age: " + json_data.getInt("Age"));
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
et_Text.setText("");
//and clear the EditText control
} else {
// Hey user, this went horribly wrong
}
}
return true;
}
return false;
}
});
}
}