adapter is null when calling notifyDataSetChanged() onResume() - android

I have a fragment that contains a listView that i want to be updated whenever a new record is added. Im trying to call .notifyDataSetChanged() in onResume() in fragment but the adapter = null.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_log,
container, false);
exmaplePrefs = this.getActivity().getSharedPreferences(PREFS, 0);
json = exmaplePrefs.getString("jsonString", "cant find json");
JSONObject MainObj = null;
JSONArray JsonArray = null;
try {
MainObj = new JSONObject(json);
JsonArray = MainObj.getJSONArray("Events");
for(int i = 0; i < JsonArray.length(); i++){
JSONObject c = JsonArray.getJSONObject(i);
// Storing JSON item in a Variable
String time = c.getString("time");
String event = c.getString("event");
String player = c.getString("player");
String from[] = {"time","event", "player"};
int to[] = {R.id.time,R.id.event, R.id.player};
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put("time", time);
map.put("event", event);
map.put("player",player);
newItemlist.add(map);
listV=(ListView)rootView.findViewById(android.R.id.list);
adapter = new SimpleAdapter(getActivity(), newItemlist, R.layout.custom_list_row, from, to);
listV.setAdapter(adapter);
}
} catch (Exception e) {
// TODO: handle exception
System.out.print("ERROR");
}
return rootView;
}
#Override
public void onResume(){
super.onResume();
System.out.println("worked");
if (adapter != null){
adapter.notifyDataSetChanged();
}
}
I think this is something to do with the adapter being created onCreateView() and is not visible when I return to the Fragment.

Looking at this, I see a few problems.
It's generally very poor practice to catch ( Exception ex). Try catching only the specific Exceptions you are worried about, it makes fixing problems easier.
Why is your ArrayAdapter created inside of a for loop? You probably wand something like this:
ArrayList list=new ArrayList(); //Specify what type of value is in the ArrayAdapter
adapter = new SimpleAdapter(getActivity(), newItemlist, R.layout.custom_list_row,list);
listV.setAdapter(adapter);
MainObj = new JSONObject(json);
JsonArray = MainObj.getJSONArray("Events");
for(int i = 0; i < JsonArray.length(); i++){
JSONObject c = JsonArray.getJSONObject(i);
// Storing JSON item in a Variable
String time = c.getString("time");
String event = c.getString("event");
String player = c.getString("player");
String from[] = {"time","event", "player"};
int to[] = {R.id.time,R.id.event, R.id.player};
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put("time", time);
map.put("event", event);
map.put("player",player);
newItemlist.add(map);
listV=(ListView)rootView.findViewById(android.R.id.list);
adapter.add(map);
}
I'm not quite sure what SimpleArrayAdapter is, but you want to create a new one once outside of the loop, and add things to it inside of the loop most likely, re-creating it seems like a poor choice. You'll probably need to do some playing with the adapter.add(map) command in particular, but this general pattern should help. You'll also need to change the ArrayList list to something like ArrayList<String> list=new ArrayList<String>(), to whatever your ArrayAdapter is storing (Looks like HashMap<String,String>)

If an Exception is thrown, you will directly move to the catch block, hence skipping adapter's initialization. This probably means that there is an error parsing your JSON string.

Related

Retrieve data on list view and go to specific class base from the data that click

I have table in mysql database (tbl_category) which have field names "Id","Category". The data is retrieve/fetch successfully already. i found that tutorial from here https://www.simplifiedcoding.net/android-mysql-tutorial-to-perform-basic-crud-operation/ . In that tutorial their is a Intent function, which means that when the listview is retrieve the data from tbl_catagory, user can click the data and go to (sample.class). But consider that i fetch three(3) data (Picture,Music,Video). What i want to do is when i click Picture it go to Picture.class, the same as Music goes to Music.class and Videos.class.
here how it show the data
private void showEmployee(){
JSONObject jsonObject = null;
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String, String>>();
try {
jsonObject = new JSONObject(JSON_STRING);
JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY);
for(int i = 0; i<result.length(); i++){
JSONObject jo = result.getJSONObject(i);
//String id = jo.getString(Config.TAG_ID);
String name = jo.getString(Config.TAG_CAT);
HashMap<String,String> employees = new HashMap<>();
// employees.put(Config.TAG_ID,id);
employees.put(Config.TAG_CAT,name);
list.add(employees);
}
} catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(
lec.this, list, R.layout.list_item,
new String[]{Config.TAG_ID,Config.TAG_CAT},
new int[]{R.id.id, R.id.name});
listView.setAdapter(adapter);
}
from here where intent occur
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(this, fetching_calculus.class);
HashMap<String,String> map =(HashMap)parent.getItemAtPosition(position);
String empId = map.get(Config.TAG_CAT).toString();
intent.putExtra(Config.EMP_ID,empId);
startActivity(intent);
}
your help will enhance my knowledge as a beginner android developer.

How to output json to a single textview not in a listview

kinda new to android. I am outputing json to a listview and it is working, now my problem is how do i output a single textview that is not in a listview?
Here is my code
private void showResult1(){
JSONObject jsonObject = null;
ArrayList<HashMap<String,String>> list = new ArrayList<>();
try {
jsonObject = new JSONObject(JSON_STRING);
JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY1);
for(int i = 0; i<result.length(); i++){
JSONObject jo = result.getJSONObject(i);
String ss_update_time = jo.getString(Config.TAG_ss_update_time);
HashMap<String,String> match = new HashMap<>();
match.put(Config.TAG_ss_update_time, ss_update_time);
list.add(match);
}
} catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(
Standings.this, list, R.layout.standings,
new String[]{Config.TAG_ss_update_time},
new int[]{ R.id.ss_update_time});
TextView.setAdapter(adapter);
}
I dont know what to change in the setAdapter. It just gives me a red error
You have to convert your JSON response into a String and then set it in your textView. It may look like this.
TextView yourTextView = (TextView) findViewById(R.id.your_textview);
StringBuilder stringBuilder = new StringBuilder();
for (HashMap<String, String> elementInList : list) {
for (String value : elementInList.values()) {
stringBuilder.append(value);
}
}
textView.setText(stringBuilder.toString());
Long story short: ListAdapter is an object used to work with ListView. You don't need to create List Adapter to display Json string using TextView.
So to show String output you just need to do this:
TextView.setText(some_string_variable);
Hope I have understood you correctly.

how to parse JSONArray in android NullPointerException

I want to parse jsonObject passed by another activity
intent.putextra("result", json.toString());
It shows everything right with name, branch and session. but it shows NullPointerException while fetching array. at here
mSubList.add(map);
this array has 6 rows.
this is my code. please tell me exactly where Im wrong.
JSONObject json;
ListView sub_list;
private JSONArray mComments = null;
private ArrayList<HashMap<String, String>> mSubList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result_page);
name = (TextView)findViewById(R.id.name_roll);
branch= (TextView)findViewById(R.id.branchname);
session = (TextView)findViewById(R.id.Session);
sub_list = (ListView)findViewById(R.id.sub_list);
try {
json = new JSONObject(getIntent().getStringExtra("result"));
name.setText(json.getString("REGNO")+" - "+json.getString("STUDENTNAME"));
branch.setText(json.getString("BRANCHNAME"));
session.setText(json.getString("SESSIONNAME"));
mComments = json.getJSONArray("DATA");
// looping through all subjects according to the json object returned
for (int i = 0; i < mComments.length(); i++) {
JSONObject c = mComments.getJSONObject(i);
// gets the content of each tag
String code = c.getString("CCODE");
String subject = c.getString("COURSENAME");
String passfail = c.getString("PASSFAIL");
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
map.put("CCODE", code);
map.put("COURSENAME", subject);
map.put("PASSFAIL", passfail);
// adding HashList to ArrayList
mSubList.add(map);
}
ListAdapter adapter = new SimpleAdapter(this, mSubList,
R.layout.singlesubject, new String[] { "CCODE", "COURSENAME",
"PASSFAIL" }, new int[] { R.id.sub_id, R.id.sub_name,R.id.sub_res });
sub_list.setAdapter(adapter);
}catch(Exception e){
e.printStackTrace();
}
}
}
if I want to change each listitem background(R.layout.singlesubject) if "PASSFAIl"=P then Green color else Red color. then what changes i have to do ?
mSubList.add(map);
this line of code is failing because you do not initialize the array before adding the map
You can initialize it by using...
mSubList = new ArrayList<Hashmap<String, String>>();
init your mSubList before add item
mSubList = new ArrayList<HashMap<String, String>>();
I think you forgot to initialize mSubList before adding data to it:
mSubList = new ArrayList<HashMap<String, String>>();

JSONArray alternative in Android

I'm attempting to parse a string that contains an array of JSON objects, but the org.json.JSONArray is not supported until the API 19 (Kit-Kat) operating system. For obvious reasons I need to figure out a way around this. Is there a better alternative to this? Or am I using this method incorrectly?
Here is the code that keeps telling me I need API 19 or higher:
protected void onPostExecute(JSONArray result) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
info = new JSONArray(result);
for(int i = 0; i < info.length(); i++){
JSONObject c = info.getJSONObject(i);
// Storing JSON item in a Variable
String title = c.getString(TAG_TITLE);
String article = c.getString(TAG_ARTICLE);
String timestamp = c.getString(TAG_TIMESTAMP);
String datestring = c.getString(TAG_DATESTRING);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TITLE, title);
map.put(TAG_ARTICLE, article);
map.put(TAG_TIMESTAMP, timestamp);
map.put(TAG_DATESTRING, datestring);
oslist.add(map);
list=(ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,
R.layout.list_v,
new String[] { TAG_TITLE,TAG_ARTICLE, TAG_TIMESTAMP,TAG_DATESTRING }, new int[] {
R.id.title,R.id.article, R.id.timestamp,R.id.date_string});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at "+oslist.get(+position).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
btw I am using an AsyncTask to put the information into a ListView. I have another class to fetch the result of the webpage. Thanks!
The new API 19 function you are using is:
info = new JSONArray(result);
Since result is already an JSONArray, why do you need to create another?
Dude try this framework is much better
https://code.google.com/p/google-gson/
or
http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html
Here is a solution under 19API lvl:
First of all. Make a Gson obj. --> Gson gson = new Gson();
Second step is get your jsonObj as String with StringRequest(instead of JsonObjectRequest)
The last step to get JsonArray...
YoursObjArray[] yoursObjArray = gson.fromJson(response, YoursObjArray[].class);

How to parse JSON data to Android?

I have followed a tutorial online and tweaked some of the code, I would like the application to read information from a different location. Currently the app is correctly reading the data from here. Now I would like to read data from here. I'm looking to attain Observation Time, Temp_C & Visibility, I imagine I would need to change my code within the try { bracket in order to read this data? Any suggestions?
public class MainActivity extends ListActivity {
// url to make request
private static String url = "http://api.androidhive.info/contacts/";
// JSON Node names
private static final String TAG_DATA = "contacts";
private static final String TAG_OBSERV = "name";
private static final String TAG_TEMP = "email";
private static final String TAG_VISIB = "gender";
// contacts JSONArray
JSONArray contacts = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParse jParser = new JSONParse();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
contacts = json.getJSONArray(TAG_DATA);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String name = c.getString(TAG_OBSERV);
String email = c.getString(TAG_TEMP);
String gender = c.getString(TAG_VISIB);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_OBSERV, name);
map.put(TAG_TEMP, email);
map.put(TAG_VISIB, gender);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
// Updating parsed JSON data into ListView
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.list_item,
new String[] { TAG_OBSERV, TAG_TEMP, TAG_VISIB }, new int[] {
R.id.name, R.id.email, R.id.mobile });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.email)).getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(TAG_OBSERV, name);
in.putExtra(TAG_TEMP, cost);
in.putExtra(TAG_VISIB, description);
startActivity(in);
}
});
}
}
How to parse JSON data to Android?
So at first you should move your code where you are attempt to perfrom network connection(fetching data from JSON) to background Thread. Actually you're doing it at Main(UI) Thread and it's not very good and correct. If your app will be installed on a device that runs on Android 3.0+ you will get NetworkOnMainThreadException and it's not nice, ins't?
Second, save your JSON and make some formatting to see its structure better. Multiset bracket { indicates JSONObject and bracket [ indicated JSONArray.
Now you should be able to parse JSON. Now i write you a little snippet of code how to start:
JSONObject o = new JSONObject(sourceString);
if (o != null) {
JSONObject data = o.getJSONObject("data"); // getting JSONObject with key data
if (data != null) {
JSONArray current = data.getJSONArray("current_condition");
}
}
...
The easiest and prettiest way would be to create a DTO with the wanted properties and then use a library such as Jackson or Gson to map the JSON to object(s). Then it would be 2 lines of code instead of that 'manual parsing'.
Here is the way you should parse and get your values from that json :
JSONObject mMainObject = new JSONObject(myResponseString);
if(mMainObject != null){
JSONObject data = mMainObject.getJSONObject("data");
if(data != null){
JSONArray currentCondition = data.getJSONArray("current_condition");
if(currentCondition != null){
for(int i = 0; i < currentCondition.lenght(); i++){
JSONObject obj = currentCondition.get(i);
if(obj != null){
String observation_time = obj.getString("observation_time");
String temp_C = obj.getString("temp_C");
String visibility = obj.getString("visibility");
}
}
}
}
}
Doing that you should consider the proper way to download the data from internet using AsyncTask for example. In this way it will not block your UI and your app will be more responsive.
Hope this help! : )

Categories

Resources