Google Places API on Android: No route to host - java

I am using google places api in my application to show nearby food locations.
I'm using the following code:
public class Background extends AsyncTask<String, Integer, String> {
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
#Override
protected String doInBackground(String... params) {
pfr = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
lctn = "location=" + latitude + "," + longitude;
key = "&key=my key";
type = "&types=" + pfr.getString("type", "food");
radius = "&radius=" + pfr.getString("radius", "500");
sensor = "&sensor=false";
StringBuilder requesturl = new StringBuilder(googlegives);
requesturl.append(lctn);
requesturl.append(radius);
requesturl.append(type);
requesturl.append(key);
requesturl.append(sensor);
DefaultHttpClient client = new DefaultHttpClient();
HttpGet req = new HttpGet(requesturl.toString());
Log.d("create", "0");
try {
HttpResponse res = client.execute(req);
HttpEntity jsonentity = res.getEntity();
String data = EntityUtils.toString(jsonentity);
JSONObject jsonobj = new JSONObject(data);
JSONArray resarray = jsonobj.getJSONArray("results");
if (resarray.length() == 0) {
Toast.makeText(getApplicationContext(), "nothing found",
Toast.LENGTH_LONG).show();
} else {
int len = resarray.length();
for (int j = 0; j < len; j++) {
lon = resarray.getJSONObject(j).getJSONObject("geometry")
.getJSONObject("location").getDouble("lng");
lat = resarray.getJSONObject(j).getJSONObject("geometry")
.getJSONObject("location").getDouble("lat");
LatLng latLng = new LatLng(lat, lon);
googleMap.addMarker(new MarkerOptions()
.position(latLng)
.title(
resarray.getJSONObject(j).getJSONObject("name")
.toString())
.snippet(
resarray.getJSONObject(j)
.getJSONObject("formatted_address")
.toString()));
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
getting latitude and longitude as global variable for getting the user's current location, on running this application on my phone following appear in log cat
03-03 16:52:37.859: W/System.err(4780): java.net.SocketException: No route to host
03-03 16:52:37.906: W/System.err(4780): at org.apache.harmony.luni.platform.OSNetworkSystem.connect(Native Method)
03-03 16:52:37.906: W/System.err(4780): at dalvik.system.BlockGuard$WrappedNetworkSystem.connect(BlockGuard.java:357)
03-03 16:52:37.906: W/System.err(4780): at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:204)
03-03 16:52:37.914: W/System.err(4780): at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:437)
03-03 16:52:37.914: W/System.err(4780): at java.net.Socket.connect(Socket.java:1002)
03-03 16:52:37.914: W/System.err(4780): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
03-03 16:52:37.914: W/System.err(4780): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:143)
03-03 16:52:37.914: W/System.err(4780): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
03-03 16:52:37.914: W/System.err(4780): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
03-03 16:52:37.914: W/System.err(4780): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:359)
03-03 16:52:37.914: W/System.err(4780): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
03-03 16:52:37.914: W/System.err(4780): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
03-03 16:52:37.921: W/System.err(4780): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
03-03 16:52:37.921: W/System.err(4780): at com.abhishekbietcs.locomap.Mapme$Background.doInBackground(Mapme.java:258)
03-03 16:52:37.921: W/System.err(4780): at com.abhishekbietcs.locomap.Mapme$Background.doInBackground(Mapme.java:1)
03-03 16:52:37.921: W/System.err(4780): at android.os.AsyncTask$2.call(AsyncTask.java:185)
03-03 16:52:37.921: W/System.err(4780): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
03-03 16:52:37.921: W/System.err(4780): at java.util.concurrent.FutureTask.run(FutureTask.java:138)
03-03 16:52:37.921: W/System.err(4780): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
03-03 16:52:37.921: W/System.err(4780): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
03-03 16:52:37.921: W/System.err(4780): at java.lang.Thread.run(Thread.java:1019)
Why is this exception being thrown? How can I get rid of it?

java.net.SocketException: No route to host.
This exception occur when there is no route to connect to host.
I found your problem here.
key = "&key=my key";
Replace this with
String APIKEY="AIzaSyDcLMS0IKQL3N76rO-aD2thfO46r96OCQI";
key = "&key=" + APIKEY;
and you have made wrong link.
Your link:
https://maps.googleapis.com/maps/api/place/nearbysearch/output?jsonlocation=25.4509294,78.630043&radius=15000&types=food&key=key&sensor=false
Link must be like:
String url = https://maps.googleapis.com/maps/api/place/search/json?location=25.4509294,78.630043&radius=15000&types=food&key=AIzaSyDcLMS0IKQL3N76rO-aD2thfO46r96OCQI&sensor=false
To get JSON you can use my code.
String data = getUrlContents(url); //Calling method
Definition of Method.
private String getUrlContents(String Url)
{
StringBuilder content = new StringBuilder();
try {
URL url = new URL(Url);
URLConnection urlConnection = url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()), 8);
String line;
while ((line = bufferedReader.readLine()) != null)
{
content.append(line + "\n");
}
bufferedReader.close();
}
catch (Exception e) {
e.printStackTrace();
}
return content.toString();
}

Related

releaseEncoder MediaMuxer in android 4.1

I have created an application containing image to video maker and i using MediaMuxer to creating video from sequence of images but SlideEncoder add second image to auto close MediaMuxer and application is crush.
05-22 07:58:33.691 6091-6122/com.aspiration.imagetovideomaker E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #2
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
Caused by: java.lang.IllegalStateException
at android.media.MediaCodec.native_configure(Native Method)
at android.media.MediaCodec.configure(MediaCodec.java:257)
at com.aspiration.imagetovideomaker.encoding.SlideEncoder.prepareEncoder(SlideEncoder.java:57)
at com.aspiration.imagetovideomaker.ImageToVideo$EncodingTask.doInBackground(ImageToVideo.java:221)
at com.aspiration.imagetovideomaker.ImageToVideo$EncodingTask.doInBackground(ImageToVideo.java:205)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:137) 
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569) 
at java.lang.Thread.run(Thread.java:856) 
here my video creation code:
SlideEncoder slideEncoder = new SlideEncoder();
try {
slideEncoder.prepareEncoder(outputFile);
Bitmap prevBm = null;
dialog.setMax(MyApplication.bitmapList.size());
for (int idx = 0; idx < MyApplication.bitmapList.size(); idx++) {
publishProgress(String.valueOf(idx + 1));
SlideShow.init();
if (idx > 0) prevBm = MyApplication.bitmapList.get(idx - 1);
Bitmap curBm = MyApplication.bitmapList.get(idx);
for (int i = 0; i < (MyApplication.FRAME_PER_SEC * MyApplication.SLIDE_TIME); i++) {
// Drain any data from the encoder into the muxer.
slideEncoder.drainEncoder(false);
// Generate a frame and submit it.
slideEncoder.generateFrame(curBm, curBm);
//slideEncoder.generateFrame(prevBm, curBm);
}
}
slideEncoder.drainEncoder(true);
} catch (IOException e) {
e.printStackTrace();
} finally {
slideEncoder.releaseEncoder();
}
here my prepareEncoder
public void prepareEncoder(File outputFile) throws IOException {
mBufferInfo = new MediaCodec.BufferInfo();
try {
MediaFormat format = MediaFormat.createVideoFormat(MIME_TYPE, WIDTH, HEIGHT);
format.setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface);
format.setInteger(MediaFormat.KEY_BIT_RATE, MyApplication.BIT_RATE);
format.setInteger(MediaFormat.KEY_FRAME_RATE, MyApplication.FRAME_PER_SEC);
format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, IFRAME_INTERVAL);
mEncoder = MediaCodec.createEncoderByType(MIME_TYPE);
mEncoder.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
mInputSurface = mEncoder.createInputSurface();
mEncoder.start();
mMuxer = new MediaMuxer(outputFile.getPath().toString(), MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);
mTrackIndex = -1;
mMuxerStarted = false;
} catch (Exception e) {
e.printStackTrace();
Log.e("SlideEncoder", e.toString());
}
}

App has stopped working Android Jsonparser

I am trying to create list view with json .
And this is the Logcat Stacktrace
1215-1239/com.skripsi.mazdamobil E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
at java.util.concurrent.FutureTask.run(FutureTask.java:239)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.NullPointerException
at com.skripsi.mazdamobil.Data_Tipsntrick$DownloadList.doInBackground(Data_Tipsntrick.java:186)
at com.skripsi.mazdamobil.Data_Tipsntrick$DownloadList.doInBackground(Data_Tipsntrick.java:164)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask.run(FutureTask.java:234)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
            at java.lang.Thread.run(Thread.java:841)
Data_Tipsntrick.java:164
private class DownloadList extends AsyncTask<Void,Void,Void> <- line 164
{
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(Data_Tipsntrick.this);
pDialog.setMessage("Tunggu Sebentar...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
Data_Tipsntrick.java:186
protected Void doInBackground(Void... unused)
{
String url_param;
url_param="fungsi.php?pl="+filepl+"&kategori="+filekategori;
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url+url_param);
Log.d("log", "url:" + url + url_param);
try
{
JSONArray result = json.getJSONArray("result"); <<-- line 186
for (int i = 0; i < result.length(); i++)
{
JSONObject c = result.getJSONObject(i);
String id = c.getString("id");
String pesan = c.getString("pesan");
String nama_tipsntrick = c.getString("nama");
String kategori_tipsntrick= c.getString("kategori");
HashMap<String,String> map = new HashMap<String,String>();
map.put(in_id,id);
map.put(in_pesan,pesan);
map.put(in_nama,nama_tipsntrick);
map.put(in_kategori,kategori_tipsntrick);
resultList.add(map);
}
Log.d("log", "bla:" + resultList);
}
catch (JSONException e)
{
e.printStackTrace();
}
return null;
}
next
05-05 11:06:11.299 1215-1215/com.skripsi.mazdamobil E/WindowManager﹕ Activity com.skripsi.mazdamobil.Data_Tipsntrick has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{416ef190 V.E..... R.....ID 0,0-304,96} that was originally added here
android.view.WindowLeaked: Activity com.skripsi.mazdamobil.Data_Tipsntrick has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{416ef190 V.E..... R.....ID 0,0-304,96} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:345)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:239)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:281)
at com.skripsi.mazdamobil.Data_Tipsntrick$DownloadList.onPreExecute(Data_Tipsntrick.java:173)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
at android.os.AsyncTask.execute(AsyncTask.java:534)
at com.skripsi.mazdamobil.Data_Tipsntrick.onCreate(Data_Tipsntrick.java:66)
at android.app.Activity.performCreate(Activity.java:5133)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Data_Tipsntrick.java:173
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(Data_Tipsntrick.this);
pDialog.setMessage("Tunggu Sebentar...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show(); <-- line 173
}
Data_Tipsntrick.java:66
new DownloadList().execute();
What am i doing wrong.Granted i don't know much java.
JSON Response
{"result":[{"id":"7","nama":"sadasdas","kategori":"berkendara","pesan":"dasdasda‌​sdasd"},{"id":"5","nama":"Menggati Ban Bocor","kategori":"berkendara","pesan":"asdsadasdas"}]}
Well you can try this way if you are getting proper JSON response:
...
...
try {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url+url_param);
JSONArray result = json.getJSONArray("result");
if(result!=null) {
for (int i = 0; i < result.length(); i++) {
JSONObject c = (JSONObject) result.get(i);
String id = "", pesan = "", nama_tipsntrick = "", kategori_tipsntrick = "";
if (c.has("id"))
id = c.getString("id");
if (c.has("pesan"))
pesan = c.getString("pesan");
if (c.has("nam"))
nama_tipsntrick = c.getString("nama");
if (c.has("kategori"))
kategori_tipsntrick = c.getString("kategori");
HashMap<String, String> map = new HashMap<String, String>();
map.put(in_id, id);
map.put(in_pesan, pesan);
map.put(in_nama, nama_tipsntrick);
map.put(in_kategori, kategori_tipsntrick);
resultList.add(map);
}
}
Log.d("log", "bla:" + resultList);
} catch (JSONException e) {
e.printStackTrace();
}

Fatal Exception AsyncTask #2 what did I do wrong?

I have a php/mysql query working that looks up the VIN, if the VIN is in the database it returns "VIN already exists" Where did I screw up in this: Error report say Fatal Exception : AsyncTask #2 (I have code that actually works above this, problem started when I tried to rewrite this to run the php checkVin before launching the Sell page)
11-21 16:34:43.736: E/AndroidRuntime(725): FATAL EXCEPTION: AsyncTask #2
11-21 16:34:43.736: E/AndroidRuntime(725): java.lang.RuntimeException: An error occured while executing doInBackground()
11-21 16:34:43.736: E/AndroidRuntime(725): at android.os.AsyncTask$3.done(AsyncTask.java:299)
11-21 16:34:43.736: E/AndroidRuntime(725): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
11-21 16:34:43.736: E/AndroidRuntime(725): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
11-21 16:34:43.736: E/AndroidRuntime(725): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
11-21 16:34:43.736: E/AndroidRuntime(725): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
11-21 16:34:43.736: E/AndroidRuntime(725): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
11-21 16:34:43.736: E/AndroidRuntime(725): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
11-21 16:34:43.736: E/AndroidRuntime(725): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
11-21 16:34:43.736: E/AndroidRuntime(725): at java.lang.Thread.run(Thread.java:856)
11-21 16:34:43.736: E/AndroidRuntime(725): Caused by: java.lang.IllegalArgumentException: Host name may not be null
11-21 16:34:43.736: E/AndroidRuntime(725): at org.apache.http.HttpHost.<init>(HttpHost.java:83)
11-21 16:34:43.736: E/AndroidRuntime(725): at org.apache.http.impl.client.AbstractHttpClient.determineTarget(AbstractHttpClient.java:497)
11-21 16:34:43.736: E/AndroidRuntime(725): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:626)
11-21 16:34:43.736: E/AndroidRuntime(725): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:616)
11-21 16:34:43.736: E/AndroidRuntime(725): at com.mobile.donswholesale.Scan.getServerResopnse(Scan.java:272)
11-21 16:34:43.736: E/AndroidRuntime(725): at com.mobile.donswholesale.Scan.access$1(Scan.java:260)
11-21 16:34:43.736: E/AndroidRuntime(725): at com.mobile.donswholesale.Scan$4.doInBackground(Scan.java:240)
11-21 16:34:43.736: E/AndroidRuntime(725): at com.mobile.donswholesale.Scan$4.doInBackground(Scan.java:1)
11-21 16:34:43.736: E/AndroidRuntime(725): at android.os.AsyncTask$2.call(AsyncTask.java:287)
11-21 16:34:43.736: E/AndroidRuntime(725): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
11-21 16:34:43.736: E/AndroidRuntime(725): ... 5 more
private void addSellButtonListener() {
Button sell = (Button) findViewById(R.id.sell_button);
sell.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
sendDatatoServer();
}
});
}
private String formatDataAsJASON() {
JSONObject root = new JSONObject();
try {
root.put("User", userId.getText().toString());
root.put("Pword", userPass.getText().toString());
root.put("VIN", VINID.getText().toString());
return root.toString();
} catch (JSONException e) {
Log.d("JWP", "Can't format JSON");
}
return null;
}
private void sendDatatoServer() {
final String json = formatDataAsJASON();
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
return getServerResopnse(json);
}
#Override
protected void onPostExecute(String result) {
if (result == "VIN already exists") {
Toast.makeText(Scan.this,
getString(R.string.vin_exists), Toast.LENGTH_LONG)
.show();
final Intent i = new Intent(Scan.this, Scan.class);
startActivity(i);
} else {
StartSell();
}
}
}.execute();
}
private String getServerResopnse(String json) {
HttpPost post = new HttpPost("http://" + serverIp.getText().toString()
+ "/chekVIN.php");
try {
StringEntity entity = new StringEntity(json);
post.setEntity(entity);
post.setHeader("Content-type", "application/json");
DefaultHttpClient client = new DefaultHttpClient();
BasicResponseHandler handler = new BasicResponseHandler();
String response = client.execute(post, handler);
return response;
} catch (UnsupportedEncodingException e) {
Log.d("JWP", e.toString());
} catch (ClientProtocolException e) {
Log.d("JWP", e.toString());
} catch (IOException e) {
Log.d("JWP", e.toString());
}
return null;
}
private void StartSell() {
final Intent i = new Intent(Scan.this, Sell.class);
EditText editText = (EditText) findViewById(R.id.VIN);
String text = editText.getText().toString();
EditText editText2 = (EditText) findViewById(R.id.Make);
String text2 = editText2.getText().toString();
EditText editText3 = (EditText) findViewById(R.id.Model);
String text3 = editText3.getText().toString();
EditText editText4 = (EditText) findViewById(R.id.Color);
String text4 = editText4.getText().toString();
EditText editText5 = (EditText) findViewById(R.id.Year);
String text5 = editText5.getText().toString();
try {
FileOutputStream fos = openFileOutput(VinHolder,
Context.MODE_PRIVATE);
fos.write(text.getBytes());
fos.close();
FileOutputStream fos2 = openFileOutput(MakeHolder,
Context.MODE_PRIVATE);
fos2.write(text2.getBytes());
fos2.close();
FileOutputStream fos3 = openFileOutput(ModelHolder,
Context.MODE_PRIVATE);
fos3.write(text3.getBytes());
fos3.close();
FileOutputStream fos4 = openFileOutput(ColorHolder,
Context.MODE_PRIVATE);
fos4.write(text4.getBytes());
fos4.close();
FileOutputStream fos5 = openFileOutput(YearHolder,
Context.MODE_PRIVATE);
fos5.write(text5.getBytes());
fos5.close();
}
catch (Exception e) {
Log.d("DEBUGTAG", "File Not Saved" + text);
e.printStackTrace();
}
startActivity(i);
}
Because I use a Text file from another page of the app to hold a manually entered ip address, I needed to carry that info over so that the the HttpPost("http://" +serverIp.getText().toString() + "chechvin.php"); would actually have the ip address in it.
After adding:
public static final String SERVERIP= "sinfo.txt";
everything worked just fine.

KitKat Connection from URL get NullPointerException in AsyncTask

i'm new in java and android programming but i accepted a challenge launched by a friend and now i have to work hard.
I finally managed to have this type of activity working with AsyncTask but it seems to work well on all android but not on 4.4.2 KitKat.
The problem seems to be on url.openConnection and i tried many times to change the way in wich i do it but i haven't had positive results...
I have only to read file from an URL
This is my class code:
public class MenuActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
new HttpTask().execute();
}
public final class HttpTask
extends
AsyncTask<String/* Param */, Boolean /* Progress */, String /* Result */> {
private HttpClient mHc = new DefaultHttpClient();
#Override
protected String doInBackground(String... params) {
publishProgress(true);
InputStream inputstream = null;
URL url = null;
try {
url = new URL("http://somesite/prova.txt");
} catch (MalformedURLException e) {
e.printStackTrace();
}
assert url != null;
URLConnection connection = null;
try {
connection = url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputstream = httpConnection.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
ByteArrayOutputStream bytearryoutputstream = new ByteArrayOutputStream();
int i;
try {
i = inputstream.read();
while (i != -1) {
bytearryoutputstream.write(i);
i = inputstream.read();
}
inputstream.close();
} catch (IOException e) {
e.printStackTrace();
}
return bytearryoutputstream.toString();
}
#Override
protected void onProgressUpdate(Boolean... progress) {
}
#Override
protected void onPostExecute(String result) {
StringBuilder nuovafrase=new StringBuilder("");
String[] frasone=result.split("\n");
ListView listView = (ListView)findViewById(R.id.listViewDemo);
ArrayAdapter<String> arrayAdapter;
arrayAdapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.rowmenu, R.id.textViewList, frasone);
listView.setAdapter(arrayAdapter);
}
}
}
And this is the Logcat...
03-11 17:49:37.955 1277-1294/com.example.appsb.app W/System.err﹕ atjava.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
03-11 17:49:37.955 1277-1294/com.example.appsb.app W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ at java.lang.Thread.run(Thread.java:841)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ Caused by: libcore.io.GaiException: getaddrinfo failed: EAI_NODATA (No address associated with hostname)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ at libcore.io.Posix.getaddrinfo(Native Method)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ at libcore.io.ForwardingOs.getaddrinfo(ForwardingOs.java:61)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ at java.net.InetAddress.lookupHostByName(InetAddress.java:405)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ ... 18 more
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ Caused by: libcore.io.ErrnoException: getaddrinfo failed: EACCES (Permission denied)
03-11 17:49:37.959 1277-1294/com.example.appsb.app W/System.err﹕ ... 21 more
03-11 17:49:37.963 1277-1294/com.example.appsb.app W/dalvikvm﹕ threadid=11: thread exiting with uncaught exception (group=0xa4d69b20)
03-11 17:49:37.963 1277-1294/com.example.appsb.app E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: com.example.appsb.app, PID: 1277
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.NullPointerException
at com.example.appsb.app.MenuActivity$HttpTask.doInBackground(MenuActivity.java:74)
at com.example.appsb.app.MenuActivity$HttpTask.doInBackground(MenuActivity.java:33)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
              at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
             at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
             at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
             at java.lang.Thread.run(Thread.java:841)
There is a Caused by: java.lang.NullPointerException but i cannot understand why...
Thanks
It could be caused by the inputstream being null. inputstream will only be initialized if the response code is OK. So you need to check what response code is being returned. If it is not causing the error, I'd still add some code for if the response code is not OK. You don't want your app to crash if it can't connect. You should at least display a helpful error message
Example:
else{
showErrorMsg();
return null;
}
Catch FileNotFoundException when trying inputstream.read();
try {
i = inputstream.read();
while (i != -1) {
bytearryoutputstream.write(i);
i = inputstream.read();
}
inputstream.close();
} catch (FileNotFoundException e) {
Log.e("MyTag","Handling empty page...");
} catch (IOException e) {
Log.e("MyTag",e.toString());
}

Why does this FileOutputStream give a NullPointerException?

so I am running an app that creates a NullPointerException when I try to write a file.
My first activity (see below) calls the NewSet activity when the user presses the new set button. When I try to write the input in the NewSet activity, it throws a NullPointerException. Printing out fileOut displays me with it having a value of null, which it shouldn't. fileOut is declared globally, but initialized in onCreate. The Two classes are below. (... represents omitted code due to being irrelevant.)
public class MainActivity extends Activity {
static ArrayList sets;
FileOutputStream fileOut;
BufferedReader read;
String line;
ArrayAdapter<String> adapter;
ListView listView;
Intent newSetIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
newSetIntent=new Intent(this,NewSet.class);
listView=(ListView)findViewById(R.id.setList);
sets=new ArrayList();
try {
read=new BufferedReader(new BufferedReader(new InputStreamReader(openFileInput("SETS.txt"))));
fileOut=openFileOutput("SETS.txt",Context.MODE_APPEND);
} catch (FileNotFoundException e) {
System.out.println("File not found");
try {
fileOut.write("".getBytes());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
System.out.println("IOE");
// TODO Auto-generated catch block
e.printStackTrace();
}
getSets();
toList();
super.onCreate(savedInstanceState);
}
...
public void newSet(String newSetName){
System.out.println(newSetName);
sets.add(newSetName);
try {
fileOut=openFileOutput("SETS.txt",Context.MODE_APPEND);
fileOut.write(newSetName.getBytes());
fileOut.write("\n".getBytes());
} catch (IOException e) {
e.printStackTrace();
}
catch (NullPointerException NPE){
System.out.println(fileOut);
NPE.printStackTrace();
}
}
}
public class NewSet extends Activity {
EditText input;
String setName;
MainActivity main;
...
public void submit(View view){
setName=input.getText().toString();
System.out.println("CREATING SET:"+setName);
main.newSet(setName);
finish();
}
}
The full stack trace
03-03 23:08:42.183: W/System.err(8435): java.lang.NullPointerException
03-03 23:08:42.183: W/System.err(8435): at android.content.ContextWrapper.openFileOutput(ContextWrapper.java:173)
03-03 23:08:42.183: W/System.err(8435): at com.ollien.flashcards.MainActivity.newSet(MainActivity.java:112)
03-03 23:08:42.183: W/System.err(8435): at com.ollien.flashcards.NewSet.submit(NewSet.java:35)
03-03 23:08:42.193: W/System.err(8435): at java.lang.reflect.Method.invokeNative(Native Method)
03-03 23:08:42.193: W/System.err(8435): at java.lang.reflect.Method.invoke(Method.java:511)
03-03 23:08:42.193: W/System.err(8435): at android.view.View$1.onClick(View.java:3594)
03-03 23:08:42.193: W/System.err(8435): at android.view.View.performClick(View.java:4204)
03-03 23:08:42.193: W/System.err(8435): at android.view.View$PerformClick.run(View.java:17355)
03-03 23:08:42.193: W/System.err(8435): at android.os.Handler.handleCallback(Handler.java:725)
03-03 23:08:42.203: W/System.err(8435): at android.os.Handler.dispatchMessage(Handler.java:92)
03-03 23:08:42.203: W/System.err(8435): at android.os.Looper.loop(Looper.java:137)
03-03 23:08:42.203: W/System.err(8435): at android.app.ActivityThread.main(ActivityThread.java:5226)
03-03 23:08:42.203: W/System.err(8435): at java.lang.reflect.Method.invokeNative(Native Method)
03-03 23:08:42.203: W/System.err(8435): at java.lang.reflect.Method.invoke(Method.java:511)
03-03 23:08:42.203: W/System.err(8435): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
03-03 23:08:42.203: W/System.err(8435): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
03-03 23:08:42.203: W/System.err(8435): at dalvik.system.NativeStart.main(Native Method)
Exception is getting thrown in android.content.ContextWrapper class. Method is:
public FileOutputStream openFileOutput(String name, int mode) throws FileNotFoundException
{
return mBase.openFileOutput(name, mode); // Line number 173
}
Here, the only possibility I see which could result in NullPointerException is data member mBase of type Context is NULL.
Can you check if Context data member is non-null.

Categories