-1
次のコードを使用しましたが、コードを実行すると致命的な例外が発生します。これを解決するために私を案内してください。コードを実行すると致命的な例外が発生する
mainactivity.java:
package com.example.admin.sample;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity {
EditText txtName;
EditText txtDept;
EditText txtBatch;
EditText txtSem;
EditText txtReg;
EditText txtSec;
EditText txtMail;
EditText txtCreatedAt;
Button btnSave;
// Button btnDelete;
String rid;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// single product url
private static final String url_product_detials = "http://ishakthiwatt.esy.es/Student.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_STUDENT = "student";
private static final String TAG_RID = "RollNo";
private static final String TAG_NAME = "Name";
private static final String TAG_DEPT = "Dept";
private static final String TAG_BATCHYR = "BatchYear";
private static final String TAG_SEM = "Sem";
private static final String TAG_REGULATION = "Reg";
private static final String TAG_SECTION = "Section";
private static final String TAG_MAILID = "MailId";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// save button
btnSave = (Button) findViewById(R.id.btnSave);
// getting product details from intent
Intent i = getIntent();
// getting product id (pid) from intent
rid= i.getStringExtra(TAG_RID);
// Getting complete product details in background thread
new GetProductDetails().execute();
}
/**
* Background Async Task to Get complete product details
* */
class GetProductDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading product details. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting product details in background thread
* */
protected String doInBackground(String... params) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
// Check for success tag
int success;
try {
// Building Parameters
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("RollNo", rid));
// getting product details by making HTTP request
// Note that product details url will use GET request
JSONObject json = jsonParser.makeHttpRequest(
url_product_detials, "GET", params);
// check your log for json response
Log.d("Single Product Details", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully received product details
JSONArray productObj = json
.getJSONArray(TAG_STUDENT); // JSON Array
// get first product object from JSON Array
JSONObject product = productObj.getJSONObject(0);
// product with this pid found
// Edit Text
txtName = (EditText) findViewById(R.id.inputName);
txtDept = (EditText) findViewById(R.id.inputDept);
txtBatch = (EditText) findViewById(R.id.inputbtchyr);
txtSem = (EditText) findViewById(R.id.inputsem);
txtReg = (EditText) findViewById(R.id.inputreg);
txtSec = (EditText) findViewById(R.id.inputsection);
txtMail = (EditText) findViewById(R.id.inputMail);
// display product data in EditText
txtName.setText(product.getString(TAG_NAME));
txtDept.setText(product.getString(TAG_DEPT));
txtSem.setText(product.getString(TAG_SEM));
txtBatch.setText(product.getString(TAG_BATCHYR));
txtReg.setText(product.getString(TAG_REGULATION));
txtSec.setText(product.getString(TAG_SECTION));
txtMail.setText(product.getString(TAG_MAILID));
}else{
// product with pid not found
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
pDialog.dismiss();
}
}
}
JAONParser.java:
package com.example.admin.sample;
import android.util.Log;
import com.loopj.android.http.AsyncHttpClient;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static JSONArray jArr = null;
static String json = "";
static String error = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
ArrayList<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method.equals("POST")){
// request method is POST
// defaultHttpClient
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
try {
Log.e("API123"," " +convertStreamToString(httpPost.getEntity().getContent()));
Log.e("API123",httpPost.getURI().toString());
} catch (Exception e) {
e.printStackTrace();
}
HttpResponse httpResponse = httpClient.execute(httpPost);
Log.e("API123"," "+httpResponse.getStatusLine().getStatusCode());
error= String.valueOf(httpResponse.getStatusLine().getStatusCode());
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method.equals("GET")){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
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();
json = sb.toString();
Log.d("API123",json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
jObj.put("error_code",error);
} catch (JSONException e) {
Log.e("JSON Parser","Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
private String convertStreamToString(InputStream is) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
is.close();
return sb.toString();
}
}
私はこのエラーを取得しています:
FATAL EXCEPTION: main
Process: com.example.admin.sample, PID: 27267
android.os.NetworkOnMainThreadException
at
android.os.StrictMode $AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1288)
at java.net.InetAddress.lookupHostByName(InetAddress.java:432)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:253)
at java.net.InetAddress.getAllByName(InetAddress.java:215)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:147)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:169)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:124)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:366)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:627)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:538)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:516)
at com.example.admin.sample.JSONParser.makeHttpRequest(JSONParser.java:81)
at com.example.admin.sample.MainActivity$GetProductDetails$1.run(MainActivity.java:114)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5740)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:766)
I/Process: Sending signal. PID: 27267 SIG: 9`
にインターネット許可を忘れてしまったん。 http://stackoverflow.com/questions/12684739/clientprotocolexception-in-httpclient-executehttpget-responsehandler –
を参照してください。android.os.NetworkOnMainThreadException:アプリケーションがメインスレッドでネットワーク操作を実行しようとしたときにスローされる例外です。 –