I have the following code:
public String test(){
URL url = null;
try {
url = new URL("http://api.heroesofnewerth.com/player_statistics/ranked/nickname/Hieratic/?token=0CZGH8ZI7UR8J2GN");
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedReader reader = null;
String x = "";
try {
reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
for (String line; (line = reader.readLine()) != null;) {
System.out.println(line);
x = line;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
if (reader !=null) try{reader.close();} catch (IOException ignore) {
}{}
}
JsonElement root = new JsonParser().parse(x);
return x;
}
}
now i want to insert the text into the following textView.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_competetion);
TextView tv = (TextView) findViewById(R.id.competetion_text);
JsonCollector jc = new JsonCollector();
tv.setText(jc.test());
However when i try to run it. i get the following error:
FATAL EXCEPTION: main
E/AndroidRuntime(1800): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.konkurrencesigner/com.example.konkurrencesigner.CreateCompetetion}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
E/AndroidRuntime(1800): at android.app.ActivityThread.access$600(ActivityThread.java:141)
E/AndroidRuntime(1800): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
E/AndroidRuntime(1800): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(1800): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(1800): at android.app.ActivityThread.main(ActivityThread.java:5039)
E/AndroidRuntime(1800): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(1800): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(1800): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
E/AndroidRuntime(1800): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
E/AndroidRuntime(1800): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime(1800): Caused by: android.os.NetworkOnMainThreadException
E/AndroidRuntime(1800): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
E/AndroidRuntime(1800): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
E/AndroidRuntime(1800): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
E/AndroidRuntime(1800): at java.net.InetAddress.getAllByName(InetAddress.java:214)
E/AndroidRuntime(1800): at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
E/AndroidRuntime(1800): at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
E/AndroidRuntime(1800): at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)
E/AndroidRuntime(1800): at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
E/AndroidRuntime(1800): at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
E/AndroidRuntime(1800): at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:316)
E/AndroidRuntime(1800): at libcore.net.http.HttpEngine.connect(HttpEngine.java:311)
E/AndroidRuntime(1800): at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290)
E/AndroidRuntime(1800): at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:240)
E/AndroidRuntime(1800): at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:282)
Can anyone tell me why this is happening?
please note that i have already added the following line in my android manifest:
<uses-permission android:name="android.permission.INTERNET" />
You are doing HTTP communication on the main thread, that's why you're getting a NetworkOnMainThreadException. Do it in a separate thread, using an AsyncTask would be an ideal solution, here's an example of how you could implement it:
private TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_competetion);
tv = (TextView) findViewById(R.id.competetion_text);
JsonCollector jc = new JsonCollector();
// Create and execute a new AsyncTask, the TextView will
// be updated asynchronously when the task has finished.
updateTextView();
}
private void updateTextView() {
new AsyncTask<Void, Void, String>() {
#Override
/* Runs on a separate thread */
protected String doInBackground(Void... params) {
String result = null;
BufferedReader reader = null;
try {
URL url = new URL("http://api.heroesofnewerth.com/player_statistics/ranked/nickname/Hieratic/?token=0CZGH8ZI7UR8J2GN");
reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
for (String line; (line = reader.readLine()) != null;) {
System.out.println(line);
result = line;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
// Ignore
}
}
}
return result;
}
#Override
/* Runs on the UI/Main thread when doInBackground()
* has finished */
protected void onPostExecute(String result) {
if(result != null) {
// Update the TextView only if we got a result
// from the HTTP request
tv.setText(result);
}
}
}.execute();
}
If you need networking in main thread add these lines of code in the onCreate() method
StrictMode.ThreadPolicy policy =
new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Related
I am new in android.i am loading data from json. While on orientation change destroy and recreate the activity so the json loading everytime orientation changing..
I am getting the following error:
{
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.OutOfMemoryError at java.lang.AbstractStringBuilder.enlargeBuffer(AbstractStringBuilder.java:94)
at java.lang.AbstractStringBuilder.append0(AbstractStringBuilder.java:145)
at java.lang.StringBuilder.append(StringBuilder.java:202)
at org.json.JSONTokener.syntaxError(JSONTokener.java:450)
at org.json.JSONTokener.nextValue(JSONTokener.java:97)
at org.json.JSONTokener.readObject(JSONTokener.java:362)
at org.json.JSONTokener.nextValue(JSONTokener.java:100)
at org.json.JSONTokener.readObject(JSONTokener.java:385)
at org.json.JSONTokener.nextValue(JSONTokener.java:100)
at org.json.JSONTokener.readArray(JSONTokener.java:430)
at org.json.JSONTokener.nextValue(JSONTokener.java:103)
at org.json.JSONTokener.readObject(JSONTokener.java:385)
at org.json.JSONTokener.nextValue(JSONTokener.java:100)
at org.json.JSONObject.<init>(JSONObject.java:154)
at org.json.JSONObject.<init>(JSONObject.java:171)
at com.ProjectName.activities.MainActivity.get_Project_Json(MainActivity.java:238)
at com.ProjectName.activities.MainActivity.onCreate(MainActivity.java:115)
at android.app.Activity.performCreate(Activity.java:5104)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3692)
at android.app.ActivityThread.access$700(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1240)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
}
especially in JellyBean and KitKat (Device:3.2 to 4.0inches)
{
public void get_Json_Assets() {
StringBuilder sb = new StringBuilder();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(getAssets().open("Somejson.json")));
String temp;
while ((temp = br.readLine()) != null)
sb.append(temp);
} catch (OutOfMemoryError e) {
e.fillInStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (Exception e) {
e.fillInStackTrace();
}
}
all_Point_Json = sb.toString();
}
}
{`public void get_Project_Json() {
get_Json_Assets();
try {
JSONObject point_Json= new JSONObject(all_Point_Json);
JSONArray point_Chapter =point_Json.getJSONArray("chapter");
for (int i = 0; i < point_Chapter.length(); i++) {
HashMap<String, String> mPoint_Details = new HashMap<>();
mPoint_Details.put("mPoint", (String) point_Chapter.get(i));
mPoint_Details.put("mPoint_No", String.valueOf(i + 1));
All_Point.add(mPoint_Details);
}
} catch (JSONException e) {
e.fillInStackTrace();
}
}`}
First of all, your code is very messy. You should clean it up. Moreover, I don't know in which part of Activity life cycle are you calling this code. I suppose, you're doing it in onResume() or onCreate() method. Probably this *.json file contains a lot of data and you are allocating memory for it. During screen rotation, you're doing it again, after next rotation, memory is allocated again and so on. You should clean memory in onPause() method or load this data in a different way (e.g. in the Service and then pass it to Activity). In addition, you should avoid loading large files at once. You can consider loading parts of that file successively and for sure load this data in a separate thread (e.g. with AsyncTask or RxJava if you're familiar with it), because it's non-deterministic and probably a long operation.
I got error when I tried to upload all of the images. I use for to loop the process, but still got error in looping. if i don't use for, it still can upload the image but only 1 image that will be uploaded. how can I solve this?
UploadActivity.java
Intent intent = getIntent();
filePath = intent.getStringExtra("filePath");
ArrayList<String> flpath = new ArrayList<String>();
SharedPreferences prefs = getSharedPreferences("SavedFilePathsJSONArray",
Context.MODE_PRIVATE);
String myJSONArrayString = prefs.getString("SavedFilePathsJSONArray",
"");
if (!myJSONArrayString.isEmpty()) {
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(myJSONArrayString);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < jsonArray.length(); i++) {
try {
flpath.add(jsonArray.get(i).toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
flpath.add(filePath);
JSONArray mJSONArray = new JSONArray(flpath);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("SavedFilePathsJSONArray", mJSONArray.toString()).commit();
for (int i = 0; i < flpath.size(); i++) {
imgFile = new File(flpath.get(i));
if (imgFile.exists()) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath(),options);
ImageView myImage = new ImageView(this);
myImage.setMaxHeight(100);
myImage.setMaxWidth(100);
myImage.setImageBitmap(myBitmap);
layout2.addView(myImage);
}
}
private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
#Override
protected void onPreExecute() {
// setting progress bar to zero
progressBar.setProgress(0);
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
// Making progress bar visible
progressBar.setVisibility(View.VISIBLE);
// updating progress bar value
progressBar.setProgress(progress[0]);
// updating percentage value
txtPercentage.setText(String.valueOf(progress[0]) + "%");
}
#Override
protected String doInBackground(Void... params) {
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
for (int i = 0; i < flPath.size(); i++) {
File file = new File( flPath.get(i));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Config.FILE_UPLOAD_URL);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
// Adding file data to http body
entity.addPart("image", new FileBody(file));
// Extra parameters if you want to pass to server
entity.addPart("website",
new StringBody("www.androidhive.info"));
entity.addPart("email", new StringBody("abc#gmail.com"));
totalSize = entity.getContentLength();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
}
return responseString;
}
Config.Java
public class Config {
public static final String FILE_UPLOAD_URL = "http://....";
// Directory name to store captured images and videos
public static final String IMAGE_DIRECTORY_NAME = "andrd_upload";
}
error logcat
01-27 16:23:45.940: W/dalvikvm(15986): threadid=12: thread exiting with uncaught exception (group=0x40fe7438)
01-27 16:23:45.950: E/AndroidRuntime(15986): FATAL EXCEPTION: AsyncTask #1
01-27 16:23:45.950: E/AndroidRuntime(15986): java.lang.RuntimeException: An error occured while executing doInBackground()
01-27 16:23:45.950: E/AndroidRuntime(15986): at android.os.AsyncTask$3.done(AsyncTask.java:299)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
01-27 16:23:45.950: E/AndroidRuntime(15986): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.lang.Thread.run(Thread.java:856)
01-27 16:23:45.950: E/AndroidRuntime(15986): Caused by: java.lang.NullPointerException
01-27 16:23:45.950: E/AndroidRuntime(15986): at com.camerafileupload.UploadActivity$UploadFileToServer.uploadFile(UploadActivity.java:228)
01-27 16:23:45.950: E/AndroidRuntime(15986): at com.camerafileupload.UploadActivity$UploadFileToServer.doInBackground(UploadActivity.java:221)
01-27 16:23:45.950: E/AndroidRuntime(15986): at com.camerafileupload.UploadActivity$UploadFileToServer.doInBackground(UploadActivity.java:1)
01-27 16:23:45.950: E/AndroidRuntime(15986): at android.os.AsyncTask$2.call(AsyncTask.java:287)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
01-27 16:23:45.950: E/AndroidRuntime(15986): ... 5 more
01-27 16:23:46.130: D/HardwareRenderer(15986): draw surface is valid dirty= null
01-27 16:23:46.180: D/HardwareRenderer(15986): draw surface is valid dirty= null
01-27 16:23:46.220: D/HardwareRenderer(15986): draw surface is valid dirty= null
01-27 16:25:29.910: D/dalvikvm(15986): WAIT_FOR_CONCURRENT_GC blocked 0ms
01-27 16:25:29.950: D/dalvikvm(15986): GC_EXPLICIT freed 223K, 8% free 15337K/16583K, paused 2ms+4ms, total 38ms
ScreenShoot
Edit: i put the error logcat and the screenshoot of the error page (UploadActivity.java).
I have implemented a JSON Parser on a background thread and then am trying to write the data to a series of TableRows on the UI Thread using some embedded code which includes a handler to put me back on the normal UI Thread. The code continually comes back with this stack trace
Process: webmd.mmu.ac.uk.wmfinal3, PID: 6123
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
at android.view.ViewGroup.addViewInner(ViewGroup.java:3562)
at android.view.ViewGroup.addView(ViewGroup.java:3415)
at android.widget.TableLayout.addView(TableLayout.java:429)
at android.view.ViewGroup.addView(ViewGroup.java:3360)
at android.widget.TableLayout.addView(TableLayout.java:411)
at android.view.ViewGroup.addView(ViewGroup.java:3336)
at android.widget.TableLayout.addView(TableLayout.java:402)
at webmd.mmu.ac.uk.wmfinal3.MainActivity$ProgressTask$1$1.run(MainActivity.java:244)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
04-21 14:58:08.506 6199-6199/webmd.mmu.ac.uk.wmfinal3 D/gralloc_goldfish﹕ Emulator without GPU emulation detected.
04-21 14:58:11.316 6199-6215/webmd.mmu.ac.uk.wmfinal3 D/dalvikvm﹕ GC_FOR_ALLOC freed 209K, 10% free 3129K/3460K, paused 2ms, total 2ms
04-21 14:58:11.336 6199-6199/webmd.mmu.ac.uk.wmfinal3 D/AndroidRuntime﹕ Shutting down VM
04-21 14:58:11.336 6199-6199/webmd.mmu.ac.uk.wmfinal3 W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0xb0cb3b20)
04-21 14:58:11.336 6199-6199/webmd.mmu.ac.uk.wmfinal3 E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: webmd.mmu.ac.uk.wmfinal3, PID: 6199
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
at android.view.ViewGroup.addViewInner(ViewGroup.java:3562)
at android.view.ViewGroup.addView(ViewGroup.java:3415)
at android.widget.TableLayout.addView(TableLayout.java:429)
at android.view.ViewGroup.addView(ViewGroup.java:3360)
at android.widget.TableLayout.addView(TableLayout.java:411)
at android.view.ViewGroup.addView(ViewGroup.java:3336)
at android.widget.TableLayout.addView(TableLayout.java:402)
at webmd.mmu.ac.uk.wmfinal3.MainActivity$ProgressTask$1$1.run(MainActivity.java:245)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
I tried moving all the code into the AsyncTask but it then demands to be on the UI Thread.
Here is my code. Any help would be much appreciated.
protected Boolean doInBackground(final String... args) {
final TableLayout tl = (TableLayout) findViewById(R.id.table);
final TableRow v1 = new TableRow(MainActivity.this);
JSONParser jParser = new JSONParser();
String temp = "http://sandbox.kriswelsh.com/hygieneapi/hygiene.php?op=nearest&lat=" + latitude + "&long=" + longitude;
JSONArray json = jParser.getJSONFromUrl(temp);
int [] test = new int [10];
for (int i = 0; i < 10; i++) {
try {
JSONObject c = json.getJSONObject(i);
String vid = c.getString(id);
String vbn = c.getString(BusinessName);
String va1 = c.getString(Add1);
String va2 = c.getString(Add2);
String va3 = c.getString(Add3);
String vpost = c.getString(Post);
String vlong = c.getString(longitudej);
String vrate = c.getString(RatingDate);
String vratestar = c.getString(Rating);
String vlat = c.getString(latitudej);
if (vratestar.contentEquals("-1")) {
vratestar = "Exempt";
}
//testing(vbn,va1,va2,va3,vpost,vratestar);
//TableLayout tl = (TableLayout) findViewById(R.id.table);
isRunning = true;
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while (isRunning) {
try {
// Thread.sleep(10000);
mHandler.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
tl.addView(v1);
}
});
} catch (Exception e) {
// TODO: handle exception
}
}
}
}).start();
isRunning = false;
//jsonlist.add(map);
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
UPDATE: Now shows v1 initialization
Looking at your while (isRunning) loop I suppose you are trying to add the same v1 TableRow view to the TableLayout on each iteration (however, it is just a guess, because you didn't post v1 declaration). Of course, at the second time it will give you an error as it is already has parent, you should create new TableRow object each time. Going deeper, you don't need Handler which is connected to UI thread, because you are using AsyncTask, you can take advantage of the fact, that onPostExecute method is executed on the main thread. Considering it, you can write the following AsyncTask implementation:
class MyAsyncTask extends AsyncTask<Void, Void, JSONArray>{
#Override
protected JSONArray doInBackground(Void... params) {
JSONParser jParser = new JSONParser();
String temp = "http://sandbox.kriswelsh.com/hygieneapi/hygiene.php?op=nearest&lat=" + latitude + "&long=" + longitude;
JSONArray json = jParser.getJSONFromUrl(temp);
return json;
}
#Override
protected void onPostExecute(JSONArray json) {
TableLayout tl = (TableLayout) findViewById(R.id.table);
for (int i = 0; i < 10; i++) {
try {
JSONObject c = json.getJSONObject(i);
String vid = c.getString(id);
String vbn = c.getString(BusinessName);
String va1 = c.getString(Add1);
String va2 = c.getString(Add2);
String va3 = c.getString(Add3);
String vpost = c.getString(Post);
String vlong = c.getString(longitudej);
String vrate = c.getString(RatingDate);
String vratestar = c.getString(Rating);
String vlat = c.getString(latitudej);
if (vratestar.contentEquals("-1")) {
vratestar = "Exempt";
}
TableRow tableRow = new TableRow(context);
//configuring row, setting layout params
tl.addView(tableRow);
} catch (JSONException ex){
//error handling
}
}
}
}
I am getting a Java null pointer exception Unable to start receiver error. I am making an app which receives the push from the parse.com and I am getting the error for Android 4.0.3 - 4.0.4, and also when I restart the some devices..
My LogCat is
**java.lang.RuntimeException: Unable to start receiver com.omega.omegaplus.main.MyCustomReceiver: java.lang.NullPointerException
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2419)
at android.app.ActivityThread.access$1500(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1322)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:4987)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
at org.json.JSONTokener.nextValue(JSONTokener.java:94)
at org.json.JSONObject.<init>(JSONObject.java:154)
at org.json.JSONObject.<init>(JSONObject.java:171)
at com.omega.omegaplus.main.MyCustomReceiver.onReceive(MyCustomReceiver.java:30)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2408)
... 10 more**
My broadcast receiver is
#Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
String message = extras != null ? extras.getString("com.parse.Data")
: "";
Log.e("message ", " " + message);
JSONObject jObject;
try {
jObject = new JSONObject(message);
//objectId = jObject.getString("id");
time = jObject.getString("time");
msg = jObject.getString("title");
title = jObject.getString("msg");
GCMMessage gcmMessage = new GCMMessage();
//gcmMessage.setMsg_id(1);
gcmMessage.setMsg_body(msg);
gcmMessage.setMsg_title(title);
gcmMessage.setType(0);
gcmMessage.setDateTime(time);
DatabaseUtil.insertMessage(context, gcmMessage);
}
catch (JSONException e) {
e.printStackTrace();
}
}
When I reboot my phone then also it showing same error..., otherwise it is working fine.
I'll have a guess that message has the value of "" or NULL
JSONObject jObject;
try {
if (message != null && !message.equals("") {
jObject = new JSONObject(message);
//objectId = jObject.getString("id");
time = jObject.getString("time");
msg = jObject.getString("title");
title = jObject.getString("msg");
GCMMessage gcmMessage = new GCMMessage();
//gcmMessage.setMsg_id(1);
gcmMessage.setMsg_body(msg);
gcmMessage.setMsg_title(title);
gcmMessage.setType(0);
gcmMessage.setDateTime(time);
DatabaseUtil.insertMessage(context, gcmMessage);
}
}
catch (JSONException e) {
e.printStackTrace();
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Here is my structure of JSON
URL::
http://54.218.73.244:7004/DescriptionSortedPrice/
JSON ::
{
"restaurants": [
{
"Sl_no": 1,
"Person_Name": "salmanKhan",
"Image_Name": "image.jpg"
},
Adapter.java
public class Adapter extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
HashMap<String, String> resultp = new HashMap<String, String>();
public Adapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView name;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.single_item, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
name = (TextView) itemView.findViewById(R.id.title_textView_id);
// Capture position and set results to the TextViews
name.setText(resultp.get(MainActivity.NAME));
return itemView;
}
}
MainActivity.java
public class MainActivity extends Activity{
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
Adapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String NAME = "rank";
String TYPE_FILTER;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.activity_main);
listview = (ListView) findViewById(R.id.listView_id);
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(MainActivity.this);
// Set progressdialog title
//mProgressDialog.setTitle("Fetching the information");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = Parser.getJSONfromURL("http://54.218.73.244:7004/DescriptionSortedPrice/");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("restaurants");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put(MainActivity.NAME, jsonobject.getString("Person_Name"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Pass the results into ListViewAdapter.java
adapter = new Adapter(MainActivity.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
Parser.java
public class Parser {
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// 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());
}
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
}
Log::
01-01 12:13:14.600: E/log_tag(715): Error in http connection java.net.SocketException: Permission denied
01-01 12:13:14.610: E/log_tag(715): Error converting result java.lang.NullPointerException
01-01 12:13:14.620: E/log_tag(715): Error parsing data org.json.JSONException: End of input at character 0 of
01-01 12:13:14.660: W/dalvikvm(715): threadid=7: thread exiting with uncaught exception (group=0x4001d800)
01-01 12:13:14.690: E/AndroidRuntime(715): FATAL EXCEPTION: AsyncTask #1
01-01 12:13:14.690: E/AndroidRuntime(715): java.lang.RuntimeException: An error occured while executing doInBackground()
01-01 12:13:14.690: E/AndroidRuntime(715): at android.os.AsyncTask$3.done(AsyncTask.java:200)
01-01 12:13:14.690: E/AndroidRuntime(715): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
01-01 12:13:14.690: E/AndroidRuntime(715): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
01-01 12:13:14.690: E/AndroidRuntime(715): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
01-01 12:13:14.690: E/AndroidRuntime(715): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
01-01 12:13:14.690: E/AndroidRuntime(715): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
01-01 12:13:14.690: E/AndroidRuntime(715): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
01-01 12:13:14.690: E/AndroidRuntime(715): at java.lang.Thread.run(Thread.java:1096)
01-01 12:13:14.690: E/AndroidRuntime(715): Caused by: java.lang.NullPointerException
01-01 12:13:14.690: E/AndroidRuntime(715): at com.example.singleitemlistview.MainActivity$DownloadJSON.doInBackground(MainActivity.java:71)
01-01 12:13:14.690: E/AndroidRuntime(715): at com.example.singleitemlistview.MainActivity$DownloadJSON.doInBackground(MainActivity.java:1)
01-01 12:13:14.690: E/AndroidRuntime(715): at android.os.AsyncTask$2.call(AsyncTask.java:185)
01-01 12:13:14.690: E/AndroidRuntime(715): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
01-01 12:13:14.690: E/AndroidRuntime(715): ... 4 more
01-01 12:13:17.215: E/WindowManager(715): Activity com.example.singleitemlistview.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#45fbe1e8 that was originally added here
01-01 12:13:17.215: E/WindowManager(715): android.view.WindowLeaked: Activity com.example.singleitemlistview.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#45fbe1e8 that was originally added here
01-01 12:13:17.215: E/WindowManager(715): at android.view.ViewRoot.<init>(ViewRoot.java:247)
01-01 12:13:17.215: E/WindowManager(715): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
01-01 12:13:17.215: E/WindowManager(715): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
01-01 12:13:17.215: E/WindowManager(715): at android.view.Window$LocalWindowManager.addView(Window.java:424)
01-01 12:13:17.215: E/WindowManager(715): at android.app.Dialog.show(Dialog.java:241)
01-01 12:13:17.215: E/WindowManager(715): at com.example.singleitemlistview.MainActivity$DownloadJSON.onPreExecute(MainActivity.java:58)
01-01 12:13:17.215: E/WindowManager(715): at android.os.AsyncTask.execute(AsyncTask.java:391)
01-01 12:13:17.215: E/WindowManager(715): at com.example.singleitemlistview.MainActivity.onCreate(MainActivity.java:41)
01-01 12:13:17.215: E/WindowManager(715): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
01-01 12:13:17.215: E/WindowManager(715): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
01-01 12:13:17.215: E/WindowManager(715): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
01-01 12:13:17.215: E/WindowManager(715): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
01-01 12:13:17.215: E/WindowManager(715): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
01-01 12:13:17.215: E/WindowManager(715): at android.os.Handler.dispatchMessage(Handler.java:99)
01-01 12:13:17.215: E/WindowManager(715): at android.os.Looper.loop(Looper.java:123)
01-01 12:13:17.215: E/WindowManager(715): at android.app.ActivityThread.main(ActivityThread.java:4627)
01-01 12:13:17.215: E/WindowManager(715): at java.lang.reflect.Method.invokeNative(Native Method)
01-01 12:13:17.215: E/WindowManager(715): at java.lang.reflect.Method.invoke(Method.java:521)
01-01 12:13:17.215: E/WindowManager(715): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
01-01 12:13:17.215: E/WindowManager(715): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
01-01 12:13:17.215: E/WindowManager(715): at dalvik.system.NativeStart.main(Native Method)
referencing from log::
line 58:: mProgressDialog.show();
line41:: new DownloadJSON().execute();
line71:: map.put(MainActivity.NAME, jsonobject.getString("Person_Name"));
Problem:: I am not able to display the parsed items on my listview
Have you given the permission in your manifest
<uses-permission android:name="android.permission.INTERNET" />
because from your log you are getting
http connection java.net.SocketException: Permission denied
Which occurs when you don't give the internet permission and try to access internet.
From your log shows:
Error in http connection java.net.SocketException: Permission denied
Error converting result java.lang.NullPointerException
Error parsing data org.json.JSONException: End of input at character 0 of
Make sure you have given the INTERNET permission in your manifest.
<uses-permission android:name="android.permission.INTERNET" />
Also change your adapter method as below:
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
Update your parser with this code block
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, HTTP.UTF_8));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}