onItemClick not working when clicked - java

I am missing something very crucial but I can't quite see what. Can someone please assist. It's probably something really silly that I have missed but I cannot initiate my onItemClick.
onCreate....
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
actu_ip = intent.getStringExtra(IPEntry.ACTUALSMARTIP);
setContentView(R.layout.act_ipcontrol);
mainListView = (ListView) findViewById( R.id.mainListView );
String[] options = new String[] { "All in to 1", "Spare"};
ArrayList<String> optionsList = new ArrayList<String>();
optionsList.addAll( Arrays.asList(options) );
listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, optionsList);
mainListView.setAdapter( listAdapter );
try {
Toast.makeText(IPControl.this, "Please wait...Connecting...", Toast.LENGTH_SHORT).show();
new AsyncAction().execute();
} catch(Exception e) {
e.printStackTrace();
}
}
private class AsyncAction extends AsyncTask<String, Void, String> {
protected String doInBackground(String... args) {
try {
InetAddress serverAddr = InetAddress.getByName(actu_ip);
socket = new Socket(serverAddr, REDIRECTED_SERVERPORT);
OutputStreamWriter osw = new OutputStreamWriter(socket.getOutputStream());
BufferedWriter bw = new BufferedWriter(osw);
out = new PrintWriter(bw, true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (! in .ready());
readBuffer();
out.println("root\r\n");
while (! in .ready());
readBuffer();
out.println("root\r\n");
while (! in .ready());
readBuffer();
out.println("[verbose,off\r\n");
while (! in .ready());
String msg = "";
while ( in .ready()) {
msg = msg + (char) in .read();
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;//returns what you want to pass to the onPostExecute()
}
protected void onPostExecute(String result) {
Toast.makeText(IPControl.this, "Connected", Toast.LENGTH_SHORT).show();
//results the data returned from doInbackground
IPControl.this.data = result;
}
}
private String readBuffer() throws IOException {
String msg = "";
while(in.ready()) {
msg = msg + (char)in.read();
}
//System.out.print(msg);
if(msg.indexOf("SNX_COM> ") != -1) return msg.substring(0, msg.indexOf("SNX_COM> "));
else if(msg.indexOf("SCX_COM> ") != -1) return msg.substring(0, msg.indexOf("SCX_COM> "));
else return msg;
}
}
What I want to initiate...
public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
long arg3) {
try {
new AsyncAction1().execute();
} catch(Exception e) {
e.printStackTrace();
}
}
private class AsyncAction1 extends AsyncTask<String, Void, String> {
protected String doInBackground(String... args) {
try {
out.println("[c,l#,i1,o*\r\n");
//System.out.print("root\r\n");
while(! in .ready());
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;//returns what you want to pass to the onPostExecute()
}
protected void onPostExecute(String result) {
//results the data returned from doInbackground
Toast.makeText(IPControl.this, "Command Sent", Toast.LENGTH_SHORT).show();
IPControl.this.data = result;
}
}

I haven't seen setOnItemClickListener method for listview in your code. Have you implemented it?
Try following
mainListView.setAdapter( listAdapter );
mainListView.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
try {
new AsyncAction1().execute();
}catch(Exception e) {
e.printStackTrace();
}
});

Thanks for all your help, I fixed my problem.
I just wasn't doing things in the correct order.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
actu_ip = intent.getStringExtra(IPEntry.ACTUALSMARTIP);
setContentView(R.layout.act_ipcontrol);
mainListView = (ListView) findViewById( R.id.mainListView );
final String[] options = new String[] { "All in to 1", "Spare"};
ArrayList<String> optionsList = new ArrayList<String>();
optionsList.addAll( Arrays.asList(options) );
listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, optionsList);
mainListView.setAdapter( listAdapter );
mainListView.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
try {
if(pos == 0) {
AsyncAction1 a = new AsyncAction1();
a.setCmd("[c,l#,i1,o*\r\n");
a.execute();
}
} catch(Exception e) {
e.printStackTrace();
}
}
});
Then....
private class AsyncAction1 extends AsyncTask<String, Void, String> {
String cmd;
public void setCmd(String c) {
cmd = c;
}
protected String doInBackground(String... args) {
try {
out.println(cmd);
//System.out.print("root\r\n");
while(! in .ready());
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;//returns what you want to pass to the onPostExecute()
}
protected void onPostExecute(String result) {
//results the data returned from doInbackground
Toast.makeText(IPControl.this, "Command Sent", Toast.LENGTH_SHORT).show();
IPControl.this.data = result;
}
}
}

Related

JSON ListView filter not working

So I've got a project to make a simple job board app. I've retrieved my JSON data and have it displaying on my app but I want to be able to use a SearchView filter but I don't know how to access my SimpleAdapter from outside of an inner-class
Here is my code:
public class jobcategories extends Activity{
private TextView jobData;
private ProgressDialog myprocessingdialog;
ArrayAdapter<String> adapter;
ArrayList<HashMap<String, String>> jobList;
private ListView lv;
private SearchView sv;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.jobcategories);
myprocessingdialog = new ProgressDialog(this);
jobList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
sv = (SearchView) findViewById(R.id.search);
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String text) {
return false;
}
#Override
public boolean onQueryTextChange(String text) {
adapter.getFilter().filter(text);
return false;
}
});
new JSONTask().execute("https://apidata.com");
}
public class JSONTask extends AsyncTask<String,String, String>{
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
//Showing Progress dialogue
myprocessingdialog.setTitle("Please Wait..");
myprocessingdialog.setMessage("Loading");
myprocessingdialog.setCancelable(false);
myprocessingdialog.setIndeterminate(false);
myprocessingdialog.show();
}
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try{
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while((line = reader.readLine()) != null){
buffer.append(line);
}
String finalJson = buffer.toString();
JSONArray parentObject = new JSONArray(finalJson);
for (int i=0; i < parentObject.length(); i++) {
JSONObject job = parentObject.getJSONObject(i);
String JobTitle = job.getString("title");
String JobLocation = job.getString("location");
String finalTitle = JobTitle + " in " + JobLocation;
String JobCompany = "advert by "+job.getString("company");
String JobDescription = job.getString("description");
String JobApply = "How to Apply: " + job.getString("apply");
HashMap<String, String> jobs = new HashMap<>();
jobs.put("title", finalTitle);
jobs.put("company", JobCompany);
jobs.put("description", JobDescription);
jobs.put("apply", JobApply);
jobList.add(jobs);
}
}catch (MalformedURLException e){
Toast.makeText(getApplicationContext(), "Error...the job server is down..." + e.toString(), Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "error parsing..." + e.toString(), Toast.LENGTH_LONG).show();
} finally {
if(connection != null) {
connection.disconnect();
}
try {
if(reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String results) {
super.onPostExecute(results);
myprocessingdialog.cancel();
ListAdapter adapter = new SimpleAdapter(
jobcategories.this, jobList,
R.layout.list_item, new String[]{"title", "company", "description", "apply"},
new int[]{R.id.title, R.id.company, R.id.description, R.id.apply});
lv.setAdapter(adapter);
}
}
}
Any help would be appreciated, am pretty new to android so if there is a better way for me to filter the data then I am open to changing the code.
Create an interface called OnJsonResultListener like so:
public interface OnJsonResultListener {
void onResult(String result);
}
Then make your Activity/Fragment implement that interface and do whatever with your simple adapter and the result from there. Then make the AsyncTask take a OnJsonResultListener in the constructor. Then in the onPostExecute method, call listener.onResult(results);
This is a simple way of making a callback.

Trying to get response from server, but it only displays "Toast Server not responding"

I am trying to get response from server but it only display me toast server not supported.i don't understand what is going on here. i have assigned the api to a static variable that i declare in another class.
Code:
public class SpeakersFrag extends Fragment {
private List<SpeakersBean> dataset;
// private Context context;
private ProgressDialog progressDialog;
SessionContoller sessionContoller;
RecyclerView recyclerView;
public SpeakerAdapter speakerAdapter;
Context context;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View myview=inflater.inflate(R.layout.speakers,null);
this.context=getActivity(); //cmt ctx
this.sessionContoller=new SessionContoller(this.context);
RecyclerView recyclerView = (RecyclerView) myview.findViewById(R.id.Recycler_viewrest);
// List<String> dataSet=new ArrayList<>();
recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this.context);
recyclerView.setLayoutManager(linearLayoutManager);
//linearLayoutManager.setOrientation;
recyclerView.setLayoutManager(linearLayoutManager);
if (AppStatus.getInstance(this.context).isOnline(this.context)) {
new GetSpeakerList().execute(new Void[0]);
} else if (this.sessionContoller.getSpeakerData() != null) {
setData(this.sessionContoller.getSpeakerData());
} else {
Dialog.noInternetAlertBox(this.context);
}
// new GetSpeakerList().execute(new Void[0]);
recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this.context,new Listener()));
return myview;
}
class Listener implements RecyclerItemClickListener.ClickListener{
#Override
public void onItemClick(View view, int i) {
SpeakersBean speakersBean=SpeakersFrag.this.getSpeakerAdapter().getItem(i);
Intent in=new Intent(SpeakersFrag.this.context,SpeakerDetail.class);
in.putExtra("speaker", speakersBean);
startActivity(in);
}
}
class GetSpeakerList extends AsyncTask<Void, Void,String> {
ProgressDialog pd;
#Override
protected void onPreExecute() {
// pd = new ProgressDialog(getActivity()).show(getActivity(), "", "Loading...");
SpeakersFrag.this.progressDialog = new ProgressDialog(SpeakersFrag.this.context);
SpeakersFrag.this.progressDialog.setMessage("Loading...");
SpeakersFrag.this.progressDialog.setCancelable(false);
SpeakersFrag.this.progressDialog.show();
}
#Override
protected String doInBackground(Void... params) {
return SpeakersFrag.this.performPostCallback(Constants.Webservice.SPEAKER_API);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (!result.equals(BuildConfig.FLAVOR))
{
try
{
JSONObject jsonObject = new JSONObject(result); // set ` *emphasized text*`status code to continue the webservice as define in constants
if (jsonObject.getString("status_code").equals("100") && jsonObject.getString("message").equalsIgnoreCase("Success"))
{
System.out.println("Speaker data with Json and gson Parsing");
sessionContoller = new SessionContoller(getContext());
JSONArray jsonArray = jsonObject.getJSONArray("items"); //items
SpeakersFrag.this.dataset = (List) new Gson().fromJson(jsonArray.toString()
, new TypeToken<List<SpeakersBean>>() {}.getType());
SpeakersFrag.this.speakerAdapter = new SpeakerAdapter(SpeakersFrag.this.context, SpeakersFrag.this.dataset);
SpeakersFrag.this.recyclerView.setAdapter(SpeakersFrag.this.speakerAdapter);
SpeakersFrag.this.sessionContoller.setSpeakerData(jsonArray.toString());
}
} catch (JSONException e)
{
Log.e("SpeakerFragment", e.toString(), e);
// e.printStackTrace();
}
}
else if (SpeakersFrag.this.sessionContoller.getSpeakerData() != null) {
SpeakersFrag.this.setData(SpeakersFrag.this.sessionContoller.getSpeakerData());
}else{
Toast.makeText(getActivity(),Constants.SERVER_ERROR,Toast.LENGTH_LONG).show();
}
SpeakersFrag.dismissDialog(SpeakersFrag.this.progressDialog);
}
}
private void setData(String speakerData){
JSONException e;
try {
JSONArray jsonSpeaker = new JSONArray(speakerData);
JSONArray jarray;
{
try {
this.dataset = (List) new Gson().fromJson(jsonSpeaker.toString(), new TypeToken<TypeToken<List<SpeakersBean>>>(){}.getType());
this.speakerAdapter = new SpeakerAdapter(SpeakersFrag.this.context, SpeakersFrag.this.dataset);
this.recyclerView.setAdapter(this.speakerAdapter); //add speakerfrag
jarray=jsonSpeaker;
// ().getType());
} catch (Exception e1) {
jarray = jsonSpeaker;
e1.printStackTrace();
}
}
}catch (JSONException e3) {
e=e3;
e.printStackTrace();
}
}
public String performPostCallback(String requestURL)
{
String response=BuildConfig.FLAVOR;
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
//send post data request
HttpURLConnection connection=(HttpURLConnection) new URL(requestURL).openConnection();
connection.setReadTimeout(15000);
connection.setConnectTimeout(15000);
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setReadTimeout(15000);
OutputStream outputStream=connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8")); //UTF-8 encode the string into utf format
outputStream.flush(); //flushes the output stream and forces to any buffered device to be written out
outputStream.close(); //close pd
if (connection.getResponseCode() != ItemTouchHelper.Callback.DEFAULT_DRAG_ANIMATION_DURATION) {
return BuildConfig.FLAVOR;
}
//Read the server response
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while (true) {
String line = br.readLine(); //read server response
if (line == null) {
return response;
}
response = response + line; //Append response
System.out.println("Response request====>>>>>"+response); //response from server
}
} catch (Exception e) {
Log.e("SpeakerFragment", e.toString(), e);
return response;
}
}
public SpeakerAdapter getSpeakerAdapter(){
return this.speakerAdapter;
}
public static void dismissDialog(ProgressDialog pd) {
if (pd != null) {
try {
if (pd.isShowing()) {
pd.dismiss();
}
} catch (Exception e)
{
e.printStackTrace();
} catch (Throwable th){
th.printStackTrace();
}
}
}
----------
}
Blockquote
I think its from the server side error....
Toast.makeText(getActivity(),Constants.SERVER_ERROR,Toast.LENGTH_LONG).show();
This code is working,thats why its showing that error

unable to retrieve JSON to spinner

Hi can you guys help me because I'm stuck here like forever and everytime I'm getting my JSON from my webhost its always null on my webhost and when I'm checking the string using Log.d this error shows NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object
Here are my codes.
PHP to get JSON
<?PHP
include_once("connection.php");
session_start();
$where = '';
if (isset($_GET['driverOwner']) && isset($_GET['roles']) && isset ($_GET['driverStatus'])){
$where = " WHERE driverOwner = '".addslashes($_GET['driverOwner'])."' AND roles = '".addslashes($_GET['roles'])."' AND driverStatus = '".addslashes($_GET['driverSTatus'])."'";
}
$query = "SELECT * FROM tbl_user ".$where."";
$result = mysqli_query($conn, $query);
if($result)
{
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
echo json_encode($data);
}
mysqli_close($conn);
?>
Drivers1.java
public class Drivers1 {
int id;
String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Connector
public class Connector {
public static HttpURLConnection connect(String urlAddress){
try{
URL url = new URL(urlAddress);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
//SET PROPERTIES
con.setRequestMethod("GET");
con.setConnectTimeout(20000);
con.setReadTimeout(20000);
con.setDoInput(true);
return con;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
DataParser.java
public class DataParser extends AsyncTask<Void,Void,Integer> {
Context c;
Spinner spDriver;
String jsonData;
ProgressDialog pd;
ArrayList<String> driver = new ArrayList<>();
public DataParser(Context c, Spinner sp, String jsonData) {
this.c = c;
this.spDriver = sp;
this.jsonData = jsonData;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(c);
pd.setTitle("Fetch");
pd.setMessage("Please wait... Getting drivers");
pd.show();
}
#Override
protected Integer doInBackground(Void... voids) {
return this.parseData();
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
pd.dismiss();
if(result == 0 ){
Toast.makeText(c, "Failed", Toast.LENGTH_SHORT).show();
}else {
//BIND
ArrayAdapter adapter = new ArrayAdapter(c,android.R.layout.simple_list_item_1, driver);
spDriver.setAdapter(adapter);
spDriver.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(c, driver.get(i), Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
}
private int parseData(){
try {
JSONArray ja = new JSONArray(jsonData);
JSONObject jo = null;
driver.clear();
Drivers1 s=null;
for (int i=0;i<ja.length();i++){
jo=ja.getJSONObject(i);
int id=jo.getInt("userID");
String name=jo.getString("firstname");
s = new Drivers1();
s.setId(id);
s.setName(name);
driver.add(name);
}
return 1;
} catch (JSONException e) {
e.printStackTrace();
}
return 0;
}
}
Downloader.java
public class Downloader extends AsyncTask<Void,Void,String> {
Context c;
String urlAddress;
Spinner spDriver;
ProgressDialog pd;
public Downloader(Context c, String urlAddress, Spinner spDriver) {
this.c = c;
this.urlAddress = urlAddress;
this.spDriver = spDriver;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(c);
pd.setTitle("Fetch(Downloader)");
pd.setMessage("Please wait... Getting Drivers");
pd.show();
}
#Override
protected String doInBackground(Void... voids) {
return this.downloadData();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.d("Downloader",""+ s);
pd.dismiss();
if (s == null) {
Toast.makeText(c, "Unable to retrieve", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(c, "Success!", Toast.LENGTH_SHORT).show();
//CALL PARSER CLASS TO PARSE
DataParser parser = new DataParser(c,spDriver,s);
parser.execute();
}
}
private String downloadData(){
HttpURLConnection con = Connector.connect(urlAddress);
if(con == null){
return null;
}
InputStream is=null;
try {
is = new BufferedInputStream(con.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = "";
StringBuffer response = new StringBuffer();
if (br != null) {
while ((line = br.readLine()) != null){
response.append(line+"\n");
}
}else {
return null;
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if(is != null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
}
And on the Activity with the spinner.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Spinner spDriver = (Spinner) findViewById(R.id.spDriver);
String url = "http://carkila.esy.es/carkila/getDriver.php?driverOwner="+ pref.getString("username","")+"&roles=driver&driverStatus=active";
new Downloader(InsertActivity.this,url ,spDriver).execute();
}
Sorry for the long post but please help me. :c thaaaaanks :)
EDIT
Error when Log.d("Downlaoder",s.toString()); is tested on Downloader.java.
Process: com.example.kun.carkila, PID: 31098
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object reference
at com.example.kun.carkila.mMySQL.Downloader.onPostExecute(Downloader.java:56)
at com.example.kun.carkila.mMySQL.Downloader.onPostExecute(Downloader.java:24)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5289)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
In your DataParser.Java class result 0 was return regardless.
private int parseData(){
try {
JSONArray ja = new JSONArray(jsonData);
JSONObject jo = null;
driver.clear();
Drivers1 s=null;
for (int i=0;i<ja.length();i++){
jo=ja.getJSONObject(i);
int id=jo.getInt("userID");
String name=jo.getString("firstname");
s = new Drivers1();
s.setId(id);
s.setName(name);
driver.add(name);
}
return 1;
} catch (JSONException e) {
e.printStackTrace();
}
return 0; //here it will go on
}
Please add a log to check what was returned, if it is returning 0 you must get Failed sort of toast.

Results not showing in the ListView Android

I've been working on an android app ... I am stuck at a point ... after getting the JSON data from the internet I am having trouble to show it in the ListView ... Below is my code ...
public class MainListActivityFragment extends Fragment {
protected String[] mBlogPostTitles;
protected JSONObject mBlogData;
public static final String LOG_TAG = MainListActivityFragment.class.getSimpleName();
public static ArrayAdapter<String> titleAdapter;
public MainListActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_list, container, false);
if(isNetworkAvailable()) {
GetBlogPost getBlogPost = new GetBlogPost();
getBlogPost.execute();
} else {
Toast.makeText(getContext(),"No Network Available", Toast.LENGTH_LONG).show();
}
List<String> blogTitles = new ArrayList<>(Arrays.asList(mBlogPostTitles));
titleAdapter = new ArrayAdapter<>(
getActivity(),
R.layout.name_lst_view,
R.id.name_list_view_textview,
blogTitles
);
ListView listView = (ListView) rootView.findViewById(R.id.listview_name);
listView.setAdapter(titleAdapter);
return rootView;
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()){
isAvailable = true;
}
return isAvailable;
}
private void updateList() {
if(mBlogData == null){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Oopps");
builder.setMessage("There was an error accessing the blog ...");
builder.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}else {
try {
JSONArray jsonPosts = mBlogData.getJSONArray("posts");
mBlogPostTitles = new String[jsonPosts.length()];
for (int i = 0; i < jsonPosts.length(); i++){
JSONObject post = jsonPosts.getJSONObject(i);
String title = post.getString("title");
title = Html.fromHtml(title).toString();
mBlogPostTitles[i] = title;
}
} catch (JSONException e) {
Log.e(LOG_TAG,"Exception Caught: ",e);
}
}
}
public class GetBlogPost extends AsyncTask<Object, Void, JSONObject> {
public final int NUMBER_OF_POSTS = 5;
int responseCode = -1;
JSONObject jsonResponse = null;
#Override
protected JSONObject doInBackground(Object... params) {
try {
URL blogFeedUrl = new URL("http://www.example.com/api/get_category_posts/?slug=americancuisines&count="+NUMBER_OF_POSTS);
HttpURLConnection connection = (HttpURLConnection) blogFeedUrl.openConnection();
connection.setRequestMethod("GET");
connection.connect();
responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK){
InputStream inputStream = connection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
String blogDataJsonStr = buffer.toString();
jsonResponse = new JSONObject(blogDataJsonStr);
}else {
Log.i(LOG_TAG, "Unsuccessful HTTP Response Code: " + responseCode);
}
}
catch (MalformedURLException e){
Log.e(LOG_TAG,"Exception Caught: ",e);
}
catch (IOException e) {
Log.e(LOG_TAG, "IO Exception Caught: ",e);
}
catch (Exception e) {
Log.e(LOG_TAG,"Exception Caught: ",e);
}
return jsonResponse;
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
mBlogData = result;
updateList();
}
}
}
From the above code you can see that i am getting that data through doInBackground method of AsyncTask ... Data is coming through perfectly as I can see through the logcat ... The issue is somewhere in this method which I can't seem to figure out ..
private void updateList() {
if(mBlogData == null){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Oopps");
builder.setMessage("There was an error accessing the blog ...");
builder.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}else {
try {
JSONArray jsonPosts = mBlogData.getJSONArray("posts");
mBlogPostTitles = new String[jsonPosts.length()];
for (int i = 0; i < jsonPosts.length(); i++){
JSONObject post = jsonPosts.getJSONObject(i);
String title = post.getString("title");
title = Html.fromHtml(title).toString();
mBlogPostTitles[i] = title;
}
} catch (JSONException e) {
Log.e(LOG_TAG,"Exception Caught: ",e);
}
}
}
The above method is called in onPostExecute I mean if i print to logcat within this method I can see the results being printed but when I try to show those results in the onCreateView method results don't show up not even in the logcat ... Any help will be appreciated ... Thanks
Change your code as following:
public class MainListActivityFragment extends Fragment {
protected String[] mBlogPostTitles;
protected JSONObject mBlogData;
public static final String LOG_TAG = MainListActivityFragment.class.getSimpleName();
public static ArrayAdapter<String> titleAdapter;
ListView listView;
public MainListActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_list, container, false);
listView = (ListView) rootView.findViewById(R.id.listview_name);
if(isNetworkAvailable()) {
GetBlogPost getBlogPost = new GetBlogPost();
getBlogPost.execute();
} else {
Toast.makeText(getContext(),"No Network Available", Toast.LENGTH_LONG).show();
}
return rootView;
}
private void updateList() {
if(mBlogData == null){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Oopps");
builder.setMessage("There was an error accessing the blog ...");
builder.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}else {
try {
JSONArray jsonPosts = mBlogData.getJSONArray("posts");
mBlogPostTitles = new String[jsonPosts.length()];
for (int i = 0; i < jsonPosts.length(); i++){
JSONObject post = jsonPosts.getJSONObject(i);
String title = post.getString("title");
title = Html.fromHtml(title).toString();
mBlogPostTitles[i] = title;
}
} catch (JSONException e) {
Log.e(LOG_TAG,"Exception Caught: ",e);
}
}
}
public class GetBlogPost extends AsyncTask<Object, Void, JSONObject> {
public final int NUMBER_OF_POSTS = 5;
int responseCode = -1;
JSONObject jsonResponse = null;
#Override
protected JSONObject doInBackground(Object... params) {
try {
URL blogFeedUrl = new URL("http://www.example.com/api/get_category_posts/?slug=americancuisines&count="+NUMBER_OF_POSTS);
HttpURLConnection connection = (HttpURLConnection) blogFeedUrl.openConnection();
connection.setRequestMethod("GET");
connection.connect();
responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK){
InputStream inputStream = connection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
String blogDataJsonStr = buffer.toString();
jsonResponse = new JSONObject(blogDataJsonStr);
}else {
Log.i(LOG_TAG, "Unsuccessful HTTP Response Code: " + responseCode);
}
}
catch (MalformedURLException e){
Log.e(LOG_TAG,"Exception Caught: ",e);
}
catch (IOException e) {
Log.e(LOG_TAG, "IO Exception Caught: ",e);
}
catch (Exception e) {
Log.e(LOG_TAG,"Exception Caught: ",e);
}
return jsonResponse;
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
mBlogData = result;
updateList();
List<String> blogTitles = new ArrayList<>(Arrays.asList(mBlogPostTitles));
titleAdapter = new ArrayAdapter<String>(
getActivity(),
R.layout.name_list_view,
R.id.name_list_view_textview,
blogTitles
);
listView.setAdapter(titleAdapter);
}
}
}
Use same array list in both update and initialize so globally declare a single array list and update it in updateList() method,
Try like this,
try {
JSONArray jsonPosts = mBlogData.getJSONArray("posts");
mBlogPostTitles = new String[jsonPosts.length()];//remove this and use the
//same as you are using in adapter
for (int i = 0; i < jsonPosts.length(); i++){
JSONObject post = jsonPosts.getJSONObject(i);
String title = post.getString("title");
title = Html.fromHtml(title).toString();
mBlogPostTitles[i] = title;
}
titleAdapter.notifyDataSetChanged();//here
} catch (JSONException e) {
Log.e(LOG_TAG,"Exception Caught: ",e);
}
OR even you can use in onPostExecute
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
mBlogData = result;
updateList();
titleAdapter.notifyDataSetChanged();//here
}
find the listview : ListView listView = (ListView) rootView.findViewById(R.id.listview_name); before calling
GetBlogPost getBlogPost = new GetBlogPost();
getBlogPost.execute();
and put this line listView.setAdapter(titleAdapter); in your onPostExecute method.

Attempt to invoke virtual method 'java.io.FileOutputStream android.content.Context.openFileOutput(java.lang.String, int)' on a null object reference [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
For some reason in my application, when I try to call openFileOutput(), it throws a NullPointerException and I am not sure what is causing it. I have made sure that all the parameters of the method are not null, but for some reason my app still throws a NullPointerException. Any suggestions?
My MainActivity class
public class MainActivity extends AppCompatActivity {
private static final String TAG_NEWS_FRAGMENT = "news_fragment";
private static final String TAG_SPORTS_FRAGMENT = "sports_fragment";
Context context = MainActivity.this;
private final String[] CATEGORY_NAMES = {"news", "sports"};
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private ProgressBar mProgressBar;
private CoordinatorLayout coordinatorLayout;
private PUNewsFragment mPUNewsFragement;
private PUSportsFragment mPUSportsFragement;
private List<NewspaperMetaObject> newsItems;
private List<List<NewspaperMetaObject>> categories;
private boolean doesFileExist;
private boolean isWebsiteOnline;
private FragmentManager fm;
private ProgressBar pb;
private boolean doRefresh;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
doRefresh = false;
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
viewPager = (ViewPager) findViewById(R.id.viewpager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
Toast.makeText(this, "Loading...", Toast.LENGTH_SHORT).show();
pb = (ProgressBar) findViewById(R.id.progressBar);
try {
isWebsiteOnline = new checkWebsiteStatus().execute().get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
doesFileExist = new File(context.getFilesDir() + "/news").exists();
new RetrieveNewspaperMeta().execute(CATEGORY_NAMES);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new PUNewsFragment(), "News");
adapter.addFragment(new PUSportsFragment(), "Sports");
viewPager.setAdapter(adapter);
}
public void refresh(String[] str) {
doRefresh = true;
new RetrieveNewspaperMeta().execute(str);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
private class RetrieveNewspaperMeta extends AsyncTask<String, Integer, Wrapper> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Wrapper doInBackground(String... params) {
Document doc = null;
categories = new ArrayList<>();
if (!doesFileExist && doRefresh) {
for (int i = 0; i < params.length; i++) {
newsItems = new ArrayList<>();
try {
Log.i("DEBUG", params[i]);
URL url = new URL("http://www.dailyprincetonian.com/category/" + params[i] + "/");
doc = Jsoup.connect(url.toString()).get();
Elements content = doc.select("article.tease-post");
System.out.println();
System.out.println(content);
int count = 0;
NewspaperMetaObject parser;
while (!content.eq(count).isEmpty()) {
parser = new NewspaperMetaObject(content.eq(count));
newsItems.add(parser);
count++;
}
categories.add(newsItems);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
for (NewspaperMetaObject o : newsItems) {
try {
Elements text = Jsoup.connect(o.getDoc().select("h3.h2 a").attr("href")).get().select("section.article-content").select("div.article-bd").select("p");
o.setArticleText(text.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
return new Wrapper(categories, params);
} else {
for (int i = 0; i < params.length; i++) {
newsItems = new ArrayList<>();
try {
FileInputStream fis = openFileInput(params[i]);
ObjectInputStream is = new ObjectInputStream(fis);
newsItems = (List<NewspaperMetaObject>) is.readObject();
is.close();
fis.close();
categories.add(newsItems);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
return new Wrapper(categories, params);
}
}
#Override
protected void onProgressUpdate(Integer... values) {
}
#Override
protected void onPostExecute(final Wrapper wrapper) {
super.onPostExecute(wrapper);
android.os.Handler mHandler = new android.os.Handler();
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
if (!doRefresh) {
PUNewsFragment.newsItems = categories.get(0);
PUSportsFragment.newsItems = categories.get(1);
setupViewPager(viewPager);
tabLayout.setupWithViewPager(viewPager);
fm = getSupportFragmentManager();
mPUNewsFragement = (PUNewsFragment) fm.findFragmentByTag(TAG_NEWS_FRAGMENT);
mPUSportsFragement = (PUSportsFragment) fm.findFragmentByTag(TAG_SPORTS_FRAGMENT);
if (mPUNewsFragement == null && mPUSportsFragement == null) {
mPUNewsFragement = new PUNewsFragment();
mPUSportsFragement = new PUSportsFragment();
fm.beginTransaction().add(mPUNewsFragement, TAG_NEWS_FRAGMENT).commit();
fm.beginTransaction().add(mPUSportsFragement, TAG_SPORTS_FRAGMENT).commit();
}
} else {
for (int i = 0; i < wrapper.params.length; i++) {
switch (wrapper.params[i]) {
case "news":
PUNewsFragment.newsItems = categories.get(0);
PUNewsFragment.adapter.notifyDataSetChanged();
break;
case "sports":
PUSportsFragment.newsItems = categories.get(1);
PUSportsFragment.adapter.notifyDataSetChanged();
break;
}
}
}
if (pb != null) {
pb.setVisibility(View.GONE);
}
Log.i("DEBUG", "DONE!");
if (doRefresh) {
context = MainActivity.this;
for (int i = 0; i < wrapper.params.length; i++) {
try {
FileOutputStream fos = context.openFileOutput(wrapper.params[i], 0);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(newsItems);
os.close();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
doRefresh = false;
}
}, 1000);
}
}
private class checkWebsiteStatus extends AsyncTask<Void, Void, Boolean> {
#Override
protected Boolean doInBackground(Void... params) {
try {
URL url = new URL("http://www.dailyprincetonian.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
urlConnection.disconnect();
return true;
} catch (IOException e) {
}
return false;
}
}
private class Wrapper {
List<List<NewspaperMetaObject>> categories;
String[] params;
public Wrapper(List<List<NewspaperMetaObject>> categories, String[] params){
this.categories = categories;
this.params = params;
}
}
}
Snippet of where the Exception is being thrown
if (doRefresh) {
context = MainActivity.this;
for (int i = 0; i < wrapper.params.length; i++) {
try {
FileOutputStream fos = context.openFileOutput(wrapper.params[i], 0);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(newsItems);
//os.flush();
os.close();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
It looks like the wrapper variable is declared (therefore you can do a
for (int i = 0; i < wrapper.params.length; i++)
without any problem) but all items in the array may be null referenced, wich is the cause of the NPE.

Categories

Resources