I am making 3 fragments pages app, and have 2 diffrent fragments with http json but with same code. The app work normaly but when i go to fragment and to another then back i get force close
threadid=1: thread exiting with uncaught exception (group=0x411f42a0)
FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.fddaaf.Fragment3.updateList(Fragment3.java:55)
at com.example.fddaaf.Fragment3$thirdDownloadFilesTask.onPostExecute(Fragment3.java:83)
at com.example.fddaaf.Fragment3$thirdDownloadFilesTask.onPostExecute(Fragment3.java:1)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4898)
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:1006)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
at dalvik.system.NativeStart.main(Native Method)
this is Fragment3 class
public class Fragment3 extends Fragment {
private ArrayList<thirdFeedItem> thirdfeedList;;
private ProgressBar progresssbar;
private ListView thirdfeedListView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View thirdrootView = inflater.inflate(R.layout.third, container, false);
progresssbar = (ProgressBar)thirdrootView.findViewById(R.id.progresssBar);
String url = "";
new thirdDownloadFilesTask().execute(url);
return thirdrootView;
}
public void updateList() {
thirdfeedListView= (ListView)getActivity().findViewById(R.id.third_list);
thirdfeedListView.setVisibility(View.VISIBLE);
if (thirdfeedListView.isShown()) {
progresssbar.setVisibility(View.GONE);
}
thirdfeedListView.setAdapter(new thirdCustomListAdapter(getActivity(), thirdfeedList));
thirdfeedListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Object o = thirdfeedListView.getItemAtPosition(position);
thirdFeedItem thirdData = (thirdFeedItem) o;
Intent intent = new Intent(getActivity(), thirdFeedDetailsActivity.class);
intent.putExtra("thirdfeed", thirdData);
startActivity(intent);
}
});
}
public class thirdDownloadFilesTask extends AsyncTask<String, Integer, Void> {
#Override
protected void onPostExecute(Void result) {
if (null != thirdfeedList) {
updateList();
}
}
#Override
protected Void doInBackground(String... params) {
String url = params[0];
// getting JSON string from URL
JSONObject json = getJSONFromUrl(url);
//parsing json data
parseJson(json);
return null;
}
}
public JSONObject getJSONFromUrl(String url) {
InputStream is = null;
JSONObject jObj = null;
String json = null;
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
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();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
public void parseJson(JSONObject json) {
try {
// parsing json object
if (json.getString("status").equalsIgnoreCase("ok")) {
JSONArray posts = json.getJSONArray("posts");
thirdfeedList = new ArrayList<thirdFeedItem>();
for (int i = 0; i < posts.length(); i++) {
JSONObject post = (JSONObject) posts.getJSONObject(i);
thirdFeedItem item = new thirdFeedItem();
item.setthirdTitle(post.getString("title"));
item.setthirdDate(post.getString("description"));
item.setthirdId(post.getString("id"));
item.setthirdUrl(post.getString("url"));
item.setthirdContent(post.getString("description"));
JSONArray attachments = post.getJSONArray("attachments");
if (null != attachments && attachments.length() > 0) {
JSONObject attachment = attachments.getJSONObject(0);
if (attachment != null)
item.setthirdAttachmentUrl(attachment.getString("url"));
}
thirdfeedList.add(item);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
I checked everything, what can be a problem? thank you
Related
I am developing an android application. I'm trying to get data from a mysql database and I keep getting this error. Can't seem to figure out what is wrong. Here is my code and my logs.
Log:
02-02 17:00:40.289 89-89/system_process W/InputManagerService: Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy#41993f60
02-02 17:00:48.338 1039-1056/com.example.busscheduledatarecorder E/My Error: Error D
02-02 17:00:48.461 1039-1056/com.example.busscheduledatarecorder E/My Error: Error D
02-02 17:01:05.339 1039-1056/com.example.busscheduledatarecorder E/response string: [ 02-02 17:01:05.762 1039:0x420 E/JSON Parser ]
Error parsing data org.json.JSONException: End of input at character 1 of
02-02 17:01:06.228 1039-1039/com.example.busscheduledatarecorder D/AndroidRuntime: Shutting down VM
02-02 17:01:06.265 1039-1039/com.example.busscheduledatarecorder W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
02-02 17:01:06.398 1039-1039/com.example.busscheduledatarecorder E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.busscheduledatarecorder.MainActivity$Load_Routes.onPostExecute(MainActivity.java:407)
at com.example.busscheduledatarecorder.MainActivity$Load_Routes.onPostExecute(MainActivity.java:375)
at android.os.AsyncTask.finish(AsyncTask.java:602)
at android.os.AsyncTask.access$600(AsyncTask.java:156)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
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)
02-02 17:01:06.534 89-473/system_process W/ActivityManager: Force finishing activity com.example.busscheduledatarecorder/.MainActivity
PHP code:
<?php
$response = array();
$response["success"] = 0;
$response["message"] = "No routes found";
// include db connect class
include('db.php');
// connecting to db
$db = new DB_CONNECT();
// get all routes from route table
$result = mysql_query("SELECT * FROM route");
// check for empty result
if ($result && mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["routes"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$route = array();
$route["busRouteId"] = $row["busRouteId"];
$route["routeName"] = $row["routeName"];
// push single product into final response array
array_push($response["routes"], $route);
}
// success
$response["success"] = 1;
}
// Echo JSON anyway!
echo json_encode($response);
die();
?>
Java Code:
public class JSONParser {
String result = null;
DBHelper db;
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONParser() {}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
Log.e("My Error", "Error A " + e.toString());
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.e("My Error", "Error B " + e.toString());
} catch (IOException e) {
e.printStackTrace();
Log.e("My Error", "Error C " + e.toString());
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "ISO-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
Log.e("My Error", "Error D ");
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
Log.e("My Error", "Error D ");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
Log.e("response string",json);
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}}
MainActivity:
public class MainActivity extends Activity {
DBHelper db;
int routeloadsuccess;
JSONArray jArray = null
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinroute= (Spinner)findViewById(R.id.spinnerroute);
pb = (ProgressBar) findViewById(R.id.progressBar);
pb.setVisibility(View.INVISIBLE);
db = new DBHelper(this);
}
public void shout(String voice)
{Toast.makeText(this, voice,Toast.LENGTH_LONG).show();}
public void insertNewRoutes(int id, String routename){
//check if route exists
boolean exists = db.checkRouteforId(id), result = false;
if(exists)
{
result = db.updateRoute(id, routename);
}
else{ result = db.insertRoute(id, routename);}
if(result){routeloadsuccess = 1;}
}
private class Load_Routes extends AsyncTask<String, String, JSONObject>{
InputStream is;
String url;
private static final String TAG_ROUTE = "bus_route";
public Load_Routes()
{
is = null;
url = "http://busscheduledata.com/RouteMobile.php";
}
#Override
protected JSONObject doInBackground(String... arg0) {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
shout("Loading Routes...");
pb.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(JSONObject json) {
// TODO Auto-generated method stub
pb.setVisibility(View.INVISIBLE);
try {
// Getting JSON Array
int success = json.getInt("success");
if (success == 1) {
JSONArray JAStuff = json.getJSONArray("response");
/** CHECK THE NUMBER OF RECORDS **/
int intStuff = JAStuff.length();
if (intStuff != 0) {
for (int i = 0; i < JAStuff.length(); i++) {
JSONObject JOStuff = JAStuff.getJSONObject(i);
Log.e("ALL THE STUFF", JOStuff.toString());
// Storing JSON item in a Variable
int routeid = JOStuff.getInt("busRouteId");
String routename = JOStuff.getString("routeName");
//Set JSON Data in spinner
insertNewRoutes(routeid,routename );
}
}
}
} catch (JSONException e) {
e.printStackTrace();
shout("Loading failed");
}
}
}//end of loading route thingy
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
populateMenu(menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
applyMenuChoice(item);
return(applyMenuChoice(item) ||super.onOptionsItemSelected(item));
}
private void populateMenu(Menu menu) {
menu.add(0, SIXTEEN_ID, 0, "Get Routes");
}
private boolean applyMenuChoice(MenuItem item) {
Intent intent;
switch (item.getItemId())
{
case SIXTEEN_ID:
db.deleteAllRoutes();
Load_Routes lr = new Load_Routes();
lr.execute();
if(routeloadsuccess == 1){
shout("Loading Complete");
intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);}
return(true);
//break;
}
return true ;
}
}
Log.e("response string",json);
This line is printing: E/response string: n
Your response is "n" which is String. In the next line you are converting it into a JsonObject which will definitely throw the exception.
jObj = new JSONObject(json);
Change the response from server from String to Json
I have a jsonArray which I want to parse in my android app.
The array:-
[
{
"id": 96905,
"category": "topup",
"detail": "Full talktime of Rs.55 + 1 local airtel SMS free for 1 day",
"price": 55,
"keywords": "topup",
"updated": "2016-01-07 00:16:23.0",
"validity": "7 days",
"service": "Airtel",
"sourceUri": "https://pay.airtel.com/online-payments/recharge.jsp",
"circle": "Assam",
"talktime": 55
},
{
"id": 90397,
"category": "topup",
"price": 510,
"keywords": "topup",
"updated": "2016-01-07 00:16:23.0",
"service": "Airtel",
"sourceUri": "https://pay.airtel.com/online-payments/recharge.jsp",
"circle": "Assam",
"talktime": 520
},
{
"id": 90399,
"category": "topup",
"price": 1000,
"keywords": "topup",
"updated": "2016-01-07 00:16:23.0",
"service": "Airtel",
"sourceUri": "https://pay.airtel.com/online-payments/recharge.jsp",
"circle": "Assam",
"talktime": 1020
}]
My android Code:-
Asynctask:-
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setTitle("Android JSON Parse Tutorial");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
try {
JSONObject jo;
JSONArray ja2 = JSONfunctions.getJSONfromURL("http://app.ireff.in:9090/IreffWeb/android?service=airtel&circle=assam");
for (int i = 0; i < ja2.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jo = ja2.getJSONObject(i);
map.put("rank", jo.getString("price"));
map.put("country", jo.getString("validity"));
map.put("population", jo.getString("talktime"));
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
listview = (ListView) findViewById(R.id.listview);
adapter = new ListViewAdapter(MainActivity.this, arraylist);
listview.setAdapter(adapter);
mProgressDialog.dismiss();
}
}
JsonFunctions.java
public class JSONfunctions {
public static JSONArray getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONArray jArray = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
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());
}
// 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 JSONArray(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
}
The error I get:-
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int org.json.JSONArray.length()' on a null object reference
at com.androidbegin.jsonparsetutorial.MainActivity$DownloadJSON.doInBackground(MainActivity.java:67)
at com.androidbegin.jsonparsetutorial.MainActivity$DownloadJSON.doInBackground(MainActivity.java:39)
at android.os.AsyncTask$2.call(AsyncTask.java:292)
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:818)
The json is hosted here
I was following this tutorial for learning json parsing, but this tutorial uses jsonObject and I am not able to parse the json array.
Not a duplicate to this :-Sending and Parsing JSON Objects or this How to parse this JSON Array in android?
Let me offer an alternate solution (of sorts). A much simpler version of your existing code would be:
Updated code:
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist = new ArrayList<>();
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(TestListActivity.this);
mProgressDialog.setTitle("Android JSON Parse Tutorial");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
String url = "http://app.ireff.in:9090/IreffWeb/android?service=airtel&circle=assam";
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setConnectTimeout(30, TimeUnit.SECONDS);
okHttpClient.setReadTimeout(30, TimeUnit.SECONDS);
okHttpClient.setRetryOnConnectionFailure(true);
Request request = new Request.Builder()
.url(url)
.build();
Call call = okHttpClient.newCall(request);
try {
Response response = call.execute();
String strResult = response.body().string();
JSONArray JARoot = new JSONArray(strResult);
for (int i = 0; i < JARoot.length(); i++) {
JSONObject JORoot = JARoot.getJSONObject(i);
HashMap<String, String> map = new HashMap<>();
if (JORoot.has("category") && JORoot.getString("category").equals("topup")) {
if (JORoot.has("id")) {
map.put("id", JORoot.getString("id"));
}
if (JORoot.has("category")) {
map.put("category", JORoot.getString("category"));
}
if (JORoot.has("detail")) {
map.put("detail", JORoot.getString("detail"));
} else {
map.put("detail", null);
}
if (JORoot.has("price")) {
map.put("price", JORoot.getString("price"));
}
/** ADD THE COLLECTED DATA TO THE ARRAY LIST **/
arraylist.add(map); /* THE DATA WILL ONLY BE ADDED IF THE CATEGORY = "topup" */
}
}
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
ListView testList = (ListView) findViewById(R.id.testList);
TestListAdapter adapter = new TestListAdapter(TestListActivity.this, arraylist);
testList.setAdapter(adapter);
mProgressDialog.dismiss();
}
}
private class TestListAdapter extends BaseAdapter {
Activity activity;
// LAYOUTINFLATER TO USE A CUSTOM LAYOUT
LayoutInflater inflater = null;
// ARRAYLIST TO GET DATA FROM THE ACTIVITY
ArrayList<HashMap<String, String>> arrItem;
public TestListAdapter(Activity activity, ArrayList<HashMap<String, String>> arrItem) {
this.activity = activity;
// CAST THE CONTENTS OF THE ARRAYLIST IN THE METHOD TO THE LOCAL INSTANCE
this.arrItem = arrItem;
// INSTANTIATE THE LAYOUTINFLATER
inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return arrItem.size();
}
#Override
public Object getItem(int position) {
return arrItem.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// A VIEWHOLDER INSTANCE
ViewHolder holder;
// CAST THE CONVERTVIEW IN A VIEW INSTANCE
View vi = convertView;
// CHECK CONVERTVIEW STATUS
if (convertView == null) {
// CAST THE CONVERTVIEW INTO THE VIEW INSTANCE vi
vi = inflater.inflate(R.layout.test_item, null);
// INSTANTIATE THE VIEWHOLDER INSTANCE
holder = new ViewHolder();
/***** CAST THE LAYOUT ELEMENTS *****/
/* TOP (PRIMARY) ELEMENTS */
holder.txtPrice = (TextView) vi.findViewById(R.id.txtPrice);
holder.txtDetail = (TextView) vi.findViewById(R.id.txtDetail);
// SET THE TAG TO "vi"
vi.setTag(holder);
} else {
// CAST THE VIEWHOLDER INSTANCE
holder = (ViewHolder) vi.getTag();
}
if (arrItem.get(position).get("price") != null) {
String strPrice = arrItem.get(position).get("price");
holder.txtPrice.setText("PRICE: " + strPrice);
}
if (arrItem.get(position).get("detail") != null) {
String strDetail = arrItem.get(position).get("detail");
holder.txtDetail.setText("DETAIL: " + strDetail);
} else {
holder.txtDetail.setText("DETAIL: NA");
}
return vi;
}
private class ViewHolder {
/* TOP (PRIMARY) ELEMENTS */
TextView txtPrice;
TextView txtDetail;
}
}
For the sake of completeness, I am also including the code for the adapter. It is a simple implementation. Do clean it up / optimize it / customize as per your requirement.
This piece of code has been tested prior to being posted (see screenshot of Logs at the bottom)
This uses the OkHttp library. Add this compile statement to the dependencies section of the module's gradle file: compile 'com.squareup.okhttp:okhttp:2.5.0'. Check the link for an updated version.
The example code uses if statements considering that not every record has the same set of nodes.
You BufferReader is not working as expected in your class JSONfunctions , do some changes in your class and it should looks like
JSONfunctions.java
public class JSONfunctions {
public static JSONArray getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONArray jArray = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
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());
}
StringBuffer sb = new StringBuffer("");
try {
URL urls = new URL(url);
URLConnection urlConnection;
urlConnection = urls.openConnection();
InputStream in = urlConnection.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
System.out.println(sb);
result=sb.toString();
} catch (IOException e) {}
catch (Exception e) {}
try {
jArray = new JSONArray(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
}
and to avoid Exception check if JSONArray is not null then only it goes to run for loop like this :
JSONArray ja2 = JSONfunctions.getJSONfromURL("http://app.ireff.in:9090/IreffWeb/android? service=airtel&circle=assam");
if(ja2!=null)
for (int i = 0; i < ja2.length(); i++) {}
jsonResponse="";
for(int i = 0; i<response.length(); i++) {
JSONObject person = (JSONObject) response.get(i);
String id = person.getString("id");
String category = person.getString("category");
}
I want to display about_builder of given JSON url, but I am not able to declare properly JSONObject and JSONArray on MainActivity, so please anyone help me to display the data on TextView.
Error shown:
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.and_ws_builder/com.example.and_ws_builder.MainActivity}:
android.os.NetworkOnMainThreadException
MainActivity.java class
public class MainActivity extends Activity {
private static String url ="http://myfourwalls.in/services_microsite/project_builder.php";
private static final String TAG_Name = "about_builder";
JSONArray builder = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFormUrl(url);
try {
builder = json.getJSONArray(TAG_Name);
JSONObject c = builder.getJSONObject(0);
for (int i = 0; i < json.length(); i++) {
String name = c.getString(TAG_Name);
final TextView nam = (TextView) findViewById(R.id.txtname);
nam.setText(name);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
JSONParser.java
public class JSONParser {
static InputStream is = null;
static JSONObject jobj = null;
static String json = "";
public JSONParser() {
}
public JSONObject getJSONFormUrl(String url) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
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();
} catch (Exception e) {
Log.e("Buffer Error","Error converting result" + e.toString());
}
try {
jobj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parse","error Parsing data" + e.toString());
}
return jobj;
}
}
main_activity.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/txtname"
android:layout_width="fill_parent"
android:layout_height="100dp"/>
</RelativeLayout>
You are using Network related code in main thread. Use AsyncTask.
You are calling network calls inside the main thread means foreground which is not supported in android.So use assynctask class which will handle network calls in background.
1)inside on create method call like:
new GetJson().execute();
2) declare the following outside oncreate
private class GetJson extends AsyncTask<String, Void, String> {
JSONObject c=null;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected JSONObject doInBackground(String... params) {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFormUrl(url);
try {
builder = json.getJSONArray(TAG_Name);
c = builder.getJSONObject(0);
} catch (JSONException e) {
e.printStackTrace();
}
return c;
}
#Override
protected void onPostExecute(final JSONObject result) {
for (int i = 0; i < result.length(); i++) {
String name = result.getString(TAG_Name);
final TextView nam = (TextView) findViewById(R.id.txtname);
nam.setText(name);
}
}
I have made an application by this tutorial
http://javatechig.com/android/json-feed-reader-in-android
but when I run app in android studio there are following errors
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
at org.json.JSONTokener.nextValue(JSONTokener.java:94)
at org.json.JSONObject.<init>(JSONObject.java:156)
at org.json.JSONObject.<init>(JSONObject.java:173)
at com.example.administrator.myapplication5.FeedListActivity.getJSONFromUrl(FeedListActivity.java:127)
at com.example.administrator.myapplication5.FeedListActivity$DownloadFilesTask.doInBackground(FeedListActivity.java:85)
at com.example.administrator.myapplication5.FeedListActivity$DownloadFilesTask.doInBackground(FeedListActivity.java:67)
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:818)
This is FeedListActivity class
public class FeedListActivity extends Activity {
private ArrayList<FeedItem> feedList = null;
private ProgressBar progressbar = null;
private ListView feedListView = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_posts_list);
progressbar = (ProgressBar) findViewById(R.id.progressBar);
String url = "http://javatechig.com/api/get_category_posts/?dev=1&slug=android";
new DownloadFilesTask().execute(url);
}
public void updateList() {
feedListView= (ListView) findViewById(R.id.custom_list);
feedListView.setVisibility(View.VISIBLE);
progressbar.setVisibility(View.GONE);
feedListView.setAdapter(new CustomListAdapter(this, feedList));
feedListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Object o = feedListView.getItemAtPosition(position);
FeedItem newsData = (FeedItem) o;
Intent intent = new Intent(FeedListActivity.this, FeedDetailsActivity.class);
intent.putExtra("feed", newsData);
startActivity(intent);
}
});
}
private class DownloadFilesTask extends AsyncTask<String, Integer, Void> {
#Override
protected void onProgressUpdate(Integer... values) {
}
#Override
protected void onPostExecute(Void result) {
if (null != feedList) {
updateList();
}
}
#Override
protected Void doInBackground(String... params) {
String url = params[0];
// getting JSON string from URL
JSONObject json = getJSONFromUrl(url);
//parsing json data
parseJson(json);
return null;
}
}
public JSONObject getJSONFromUrl(String url) {
InputStream is = null;
JSONObject jObj = null;
String json = null;
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
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();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
public void parseJson(JSONObject json) {
try {
// parsing json object
if (json.getString("status").equalsIgnoreCase("ok")) {
JSONArray posts = json.getJSONArray("posts");
feedList = new ArrayList<FeedItem>();
for (int i = 0; i < posts.length(); i++) {
JSONObject post = (JSONObject) posts.getJSONObject(i);
FeedItem item = new FeedItem();
item.setTitle(post.getString("title"));
item.setDate(post.getString("date"));
item.setId(post.getString("id"));
item.setUrl(post.getString("url"));
item.setContent(post.getString("content"));
JSONArray attachments = post.getJSONArray("attachments");
if (null != attachments && attachments.length() > 0) {
JSONObject attachment = attachments.getJSONObject(0);
if (attachment != null)
item.setAttachmentUrl(attachment.getString("url"));
}
feedList.add(item);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Also, I found this answer (Android strange error) but it didn't work
I would be thankful to consider this error and help me to solve that.
I know that maybe could be stupid but one error that was bother me was:
JSONObject.put(java.lang.String, java.lang.Object)' on a null object reference
This can happen even when you have not declared your json into your doInBackground.
So when you write your code don't forget to insert:
final JSONObject jsonresponse = new JSONObject();
Give your app permission to get connected to the internet in AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
The exception is thrown here:
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
json is null, and JSONObject can't be created. Please check why json is not assigned and remains null in this code:
String json = null;
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
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();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
This is my AsyncTask:
public class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog = new ProgressDialog(GetData.this);
protected void onPreExecute() {
dialog.setMessage("Searching Database");
dialog.show();
}
protected Boolean doInBackground(final String... args) {
JSONParser jParser = new JSONParser();
// get JSON data from URL
JSONArray json = jParser.getJSONFromUrl(url);
for (int i = 0; i < json.length(); i++) {
try {
JSONObject c = json.getJSONObject(i);
String Listing_ID = c.getString(lblListing_ID);
String Event_ID = c.getString(lblEvent_ID);
String Venue_ID = c.getString(lblVenue_ID);
String Start_Date = c.getString(lblStart_Date);
String End_Date = c.getString(lblEnd_Date);
String Frequency = c.getString(lblFrequency);
HashMap<String, String> map = new HashMap<String, String>();
// Add child node to HashMap key & value
map.put(lblListing_ID, Listing_ID);
map.put(lblEvent_ID, Event_ID);
map.put(lblVenue_ID, Venue_ID);
map.put(lblStart_Date, Start_Date);
map.put(lblEnd_Date, End_Date);
map.put(lblFrequency, Frequency);
jsonlist.add(map);
}
catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
ListAdapter adapter = new SimpleAdapter(GetData.this, jsonlist,
R.layout.list_item, new String[] { lblListing_ID , lblEvent_ID,
lblVenue_ID, lblStart_Date, lblEnd_Date, lblFrequency }, new int[] {
R.id.Listing_ID, R.id.Event_ID, R.id.Venue_ID,
R.id.Start_Date, R.id.End_Date, R.id.Frequency });
setListAdapter(adapter);
// select single ListView item
lv = getListView();
}
}
And here is my JSONParser class:
public class JSONParser {
static InputStream iStream = null;
static JSONArray jarray = null;
static String json = "";
public JSONParser() {
}
public JSONArray getJSONFromUrl(String url) {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} else {
Log.e("==>", "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// Parse String to JSON object
try {
JSONObject object = new JSONObject( builder.toString());
jarray = object.getJSONArray("listings");
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON Object
return jarray;
}
}
When the url is standard like:
http://192.168.1.74/android_connect/get_venues.php
It works fine. However if i add parameters like:
http://192.168.1.74/android_connect/get_venues.php?Venue_Name=Venue Name
It gives the error saying activity has leaked window. Here is the logcat:
23915-23915/com.familiestvw.whatson E/WindowManager﹕ Activity com.familiestvw.whatson.GetData has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{42f9a980 V.E..... R......D 0,0-1026,288} that was originally added here
android.view.WindowLeaked: Activity com.familiestvw.whatson.GetData has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{42f9a980 V.E..... R......D 0,0-1026,288} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:450)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:258)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:73)
at android.app.Dialog.show(Dialog.java:287)
at com.familiestvw.whatson.GetData$ProgressTask.onPreExecute(GetData.java:84)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
at android.os.AsyncTask.execute(AsyncTask.java:534)
at com.familiestvw.whatson.GetData.onCreate(GetData.java:77)
at android.app.Activity.performCreate(Activity.java:5372)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2257)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349)
at android.app.ActivityThread.access$700(ActivityThread.java:159)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5419)
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:1187)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
at dalvik.system.NativeStart.main(Native Method)
Any ideas on what the problem is and how to fix it would be greatly appreciated.
Probably the error exists in the AsyncTask, which causes the Activity to shutdown, then when you try to open a dialog, the exception occurs. I suggest that check the earlier log, also try to print what you get from the URL.