Attempt to invoke interface method on a null object reference - java

I have class LoadJSONTask. In this class I am getting the error below.
My application is running but when I try to add progress bar in the code its not working.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: in.kalakaaristudios.json.listviewmenu, PID: 3809
java.lang.NullPointerException: Attempt to invoke interface method 'void in.kalakaaristudios.json.listviewmenu.LoadJSONTask$Listener.onLoaded(java.util.List)' on a null object reference
at in.kalakaaristudios.json.listviewmenu.LoadJSONTask$override.onPostExecute(LoadJSONTask.java:83)
at in.kalakaaristudios.json.listviewmenu.LoadJSONTask$override.access$dispatch(LoadJSONTask.java)
at in.kalakaaristudios.json.listviewmenu.LoadJSONTask.onPostExecute(LoadJSONTask.java:0)
at in.kalakaaristudios.json.listviewmenu.LoadJSONTask.onPostExecute(LoadJSONTask.java:21)
at android.os.AsyncTask.finish(AsyncTask.java:651)
at android.os.AsyncTask.access$500(AsyncTask.java:180)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5441)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)
LoadJSONTask class
package in.kalakaaristudios.json.listviewmenu;
import android.os.AsyncTask;
import android.view.View;
import android.widget.ProgressBar;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
public class LoadJSONTask extends AsyncTask<String, Void, Response> {
private MainActivity activity;
private ProgressBar dwBar;
public LoadJSONTask(MainActivity activity) {
this.activity = activity;
dwBar = (ProgressBar) activity.findViewById(R.id.progress_bar);
}
public LoadJSONTask(Listener listener) {
mListener = listener;
}
public interface Listener {
void onLoaded(List<AndroidVersion> androidList);
void onError();
}
private Listener mListener;
#Override
protected Response doInBackground(String... strings) {
try {
String stringResponse = loadJSON(strings[0]);
Gson gson = new Gson();
return gson.fromJson(stringResponse, Response.class);
} catch (IOException e) {
e.printStackTrace();
return null;
} catch (JsonSyntaxException e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
MainActivity mn = new MainActivity();
dwBar.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(Response response) {
dwBar.setVisibility(View.GONE);
if (response != null) {
mListener.onLoaded(response.getAndroid());//getting error here
} else {
mListener.onError();
}
}
private String loadJSON(String jsonURL) throws IOException {
URL url = new URL(jsonURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = in.readLine()) != null) {
response.append(line);
}
in.close();
return response.toString();
}
}
MainActivity.java
package in.kalakaaristudios.json.listviewmenu;
import android.os.AsyncTask;
import android.view.View;
import android.widget.ProgressBar;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
public class LoadJSONTask extends AsyncTask<String, Void, Response> {
private MainActivity activity;
private ProgressBar dwBar;
public LoadJSONTask(MainActivity activity) {
this.activity = activity;
dwBar = (ProgressBar) activity.findViewById(R.id.progress_bar);
}
public LoadJSONTask(Listener listener) {
mListener = listener;
}
public interface Listener {
void onLoaded(List<AndroidVersion> androidList);
void onError();
}
private Listener mListener;
#Override
protected Response doInBackground(String... strings) {
try {
String stringResponse = loadJSON(strings[0]);
Gson gson = new Gson();
return gson.fromJson(stringResponse, Response.class);
} catch (IOException e) {
e.printStackTrace();
return null;
} catch (JsonSyntaxException e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
MainActivity mn = new MainActivity();
dwBar.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(Response response) {
dwBar.setVisibility(View.GONE);
if (response != null) {
mListener.onLoaded(response.getAndroid());
} else {
mListener.onError();
}
}
private String loadJSON(String jsonURL) throws IOException {
URL url = new URL(jsonURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = in.readLine()) != null) {
response.append(line);
}
in.close();
return response.toString();
}
}

I think your issue is on this line
dwBar = (ProgressBar) activity.findViewById(R.id.progress_bar);
because you are using the activity class instance to obtain a reference to your ProgressBar View widget
You should inflate a layout that contains the ProgressBar widget and use the find to get an instance of your ProgressBar
View view = inflater.inflate(R.Layout_that_contains_progress_bar, null);
dwBar = (ProgressBar) activity.findViewById(R.id.progress_bar);
Alternatively, you can create ProgressBar programmatically like below
dwBar = new ProgressBar(activity);

Related

Trying to Populate Spinner with JSON and getting 'java.lang.Object[] java.util.Collection.toArray()' on a null object reference

I am an android newbie who is trying to populate spinner using JSON but I keep getting Null Pointer Exception -
java.lang.NullPointerException: Attempt to invoke interface method
java.lang.Object[] java.util.Collection.toArray()' on a null object
reference
I understand that this is a frequently asked question, and have looked through the other answers and solutions. I have tried initializing the List but still, am unable to fix the error.I think I am having trouble understanding where the initialization is exactly needed.
My Complete log:
07-19 09:34:54.356 11199-11337/com.genx.meghna.makdver4 D/Result is: [{"car_number":"DL 2345"},{"car_number":"DL 53546"},{"car_number":"1472"},{"car_number":"m7894"},{"car_number":"nxjvjsv"}]
07-19 09:34:54.356 11199-11337/com.genx.meghna.makdver4 D/res =: [{"car_number":"DL 2345"},{"car_number":"DL 53546"},{"car_number":"1472"},{"car_number":"m7894"},{"car_number":"nxjvjsv"}]
07-19 09:34:54.357 11199-11337/com.genx.meghna.makdver4 E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #3
Process: com.genx.meghna.makdver4, PID: 11199
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object[] java.util.Collection.toArray()' on a null object reference
at java.util.ArrayList.addAll(ArrayList.java:188)
at com.genx.meghna.makdver4.Fragments.SendCarFragment$GetData.doInBackground(SendCarFragment.java:173)
at com.genx.meghna.makdver4.Fragments.SendCarFragment$GetData.doInBackground(SendCarFragment.java:117)
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) 
My code :
package com.genx.meghna.makdver4.Fragments;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.genx.meghna.makdver4.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import static com.genx.meghna.makdver4.Fragments.LoginFragment.un;
public class SendCarFragment extends Fragment {
TextView tv1, tv2, tv3;
Spinner sp;
RadioGroup rg;
RadioButton rb1, rb2;
Button btn;
FragmentManager fm;
ArrayList<String> carList;
ArrayAdapter<String> adapter;
String res;
SharedPreferences spp;
public SendCarFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_send_car, container, false);
btn = rootView.findViewById(R.id.nextPage1);
rg = rootView.findViewById(R.id.radioGroup1);
rb1 = rootView.findViewById(R.id.rb1);
rb2 = rootView.findViewById(R.id.rb2);
sp = rootView.findViewById(R.id.spinnerSelectCar);
spp=getContext().getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (rg.getCheckedRadioButtonId() == -1) {
Toast.makeText(getContext(), "Select One Option", Toast.LENGTH_SHORT).show();
} else {
if (rb1.isChecked()) {
fm = getFragmentManager();
fm.beginTransaction().replace(R.id.container, new ServiceCenterListFragment(), "Service center").commit();
} else {
fm = getFragmentManager();
fm.beginTransaction().replace(R.id.container, new SelectionFragment(), "Select Address").commit();
}
}
}
});
return rootView;
}
public void onStart(){
super.onStart();
String username1 = spp.getString(un, "userKey");
GetData get = new GetData();
get.execute(username1);
}
class GetData extends AsyncTask<String, Void, String> {
List<String> list;
protected void onPreExecute(){
super.onPreExecute();
list=new ArrayList<>();
}
#Override
protected String doInBackground(String... params) {
{
try {
String username1 = params[0];
String link = "http://10.0.3.2//Traccar/getCars.php";
String myurl = "username=" + username1;
URL url = new URL(link);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.getOutputStream().write(myurl.getBytes());
int response = connection.getResponseCode();
Log.d("Response code", "" + response);
if (response == HttpURLConnection.HTTP_OK) {
String line;
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader br = new BufferedReader(isr);
StringBuilder buffer = new StringBuilder();
while ((line = br.readLine()) != null) {
buffer.append(line);
//res+=line;
}
Log.d("Result is", buffer.toString());
res = buffer.toString();
Log.d("res = ", res);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
try{
JSONArray jrr = new JSONArray(res);
for (int i=0; i<jrr.length(); i++) {
JSONObject obj = jrr.getJSONObject(i);
String name = obj.getString("car_number");
list.add(name);
}
} catch (JSONException e1) {
e1.printStackTrace();
}
return res;
}
protected void onPostExecute(String res) {
list.addAll(carList);
adapter = new ArrayAdapter<>(getContext(),android.R.layout.simple_list_item_1, carList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(adapter);
}
}
}
One Alternative method I tried was placing my JSON parse code in the onPostExecute() function but I kept having trouble trying to pass my array from doInBackground() to onPostExecute() which led to my onPostExecute() never being used.
Any help would be much appreciated. Thank you!
You have a carList and a list. You don't initialize or add items to carList but try to pass it to list.addAll(carList); which naturally cannot work.
Since the data is already in list you should be able to do this
class GetData extends AsyncTask<String, Void, List<String>> {
List<String> list;
protected void onPreExecute(){
super.onPreExecute();
list=new ArrayList<>();
}
#Override
protected String doInBackground(String... params) {
{
try {
String username1 = params[0];
String link = "http://10.0.3.2//Traccar/getCars.php";
String myurl = "username=" + username1;
URL url = new URL(link);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.getOutputStream().write(myurl.getBytes());
int response = connection.getResponseCode();
Log.d("Response code", "" + response);
if (response == HttpURLConnection.HTTP_OK) {
String line;
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader br = new BufferedReader(isr);
StringBuilder buffer = new StringBuilder();
while ((line = br.readLine()) != null) {
buffer.append(line);
//res+=line;
}
Log.d("Result is", buffer.toString());
res = buffer.toString();
Log.d("res = ", res);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
try{
JSONArray jrr = new JSONArray(res);
for (int i=0; i<jrr.length(); i++) {
JSONObject obj = jrr.getJSONObject(i);
String name = obj.getString("car_number");
list.add(name);
}
} catch (JSONException e1) {
e1.printStackTrace();
}
return list;
}
protected void onPostExecute(List<String> res) {
adapter = new ArrayAdapter<>(getContext(),android.R.layout.simple_list_item_1, res);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(adapter);
}
}
Note that I changed AsyncTask to AsyncTask<String, Void, List<String>> and carList is not needed.

HttpURLconnection continuously returns error - Android

Hi iam trying to post a simple json Object and get the results using Httpurlconnection. I tried but am not getting any error or any response. can some one help me to fix this. tnx.
RequestExternalResouce class
package sathyabamanan.com.duoproject.comman;
import android.content.Context;
import android.os.AsyncTask;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
/**
* Created by baman on 6/25/17.
*/
public class RequestExternalResouce extends AsyncTask<String, Void, String> {
private Context mContext;
private OnTaskDoneListener onTaskDoneListener;
private String urlStr = "";
private String requestBody = "";
public RequestExternalResouce(Context context, String url, String body, OnTaskDoneListener onTaskDoneListener) {
this.mContext = context;
this.urlStr = url;
this.requestBody= body;
this.onTaskDoneListener = onTaskDoneListener;
}
#Override
protected String doInBackground(String... params) {
try {
URL mUrl = new URL(urlStr);
HttpURLConnection httpConnection = (HttpURLConnection) mUrl.openConnection();
httpConnection.setRequestMethod("POST");
httpConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
httpConnection.setUseCaches(false);
httpConnection.setAllowUserInteraction(false);
httpConnection.setConnectTimeout(1000000);
httpConnection.setReadTimeout(1000000);
httpConnection.connect();
//get Response
int responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
DataOutputStream localDataOutputStream = new DataOutputStream(httpConnection.getOutputStream());
localDataOutputStream.writeBytes(requestBody.toString());
localDataOutputStream.flush();
localDataOutputStream.close();
BufferedReader br = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
return sb.toString();
}
} catch (IOException e) { e.printStackTrace();
} catch (Exception ex) { ex.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (onTaskDoneListener != null && s != null) {
onTaskDoneListener.onTaskDone(s);
} else
onTaskDoneListener.onError();
}
public interface OnTaskDoneListener {
void onTaskDone(String responseData);
void onError();
}
}
Activity Methods
public void sendLloginRequest(View v){
login_email = email.getText().toString();
login_password = password.getText().toString();
String getLoginUrl = getRequestBody();
new RequestExternalResouce(context, new Utility().getLoginUrl(), getLoginUrl, new RequestExternalResouce.OnTaskDoneListener() {
#Override
public void onTaskDone(String responseData) {
System.out.println("Success : in activity"+ responseData);
}
#Override
public void onError() {
System.out.println("Error : ");
}
}).execute();
}
public String getRequestBody(){
JSONObject requestBody = new JSONObject();
JSONArray scopeArray = new JSONArray();
try {
scopeArray.put("all_all");
requestBody.put("userName", login_email);
requestBody.put("password", login_password);
requestBody.put("scope", scopeArray);
requestBody.put("console", "AGENT_CONSOLE");
requestBody.put("clientID", "e8ea7bb0-5026-11e7-a69b-b153a7c332b9");
} catch (JSONException e1) {
e1.printStackTrace();
}
return requestBody.toString();
}
JSon Object
{
"userName": "sathya#gmail.com",
"password": "AD123",
"scope": [
"all_all"
],
"console": "AGENT_CONSOLE",
"clientID": "e8ea7bb0-5026-11e7-a69b-b153a7c332b9"
}
Updated the class.
package sathyabamanan.com.duoproject.comman;
import android.content.Context;
import android.os.AsyncTask;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
/**
* Created by baman on 6/25/17.
*/
public class RequestExternalResouce extends AsyncTask<String, Void, String> {
private Context mContext;
private OnTaskDoneListener onTaskDoneListener;
private String urlStr = "";
private String requestBody = "";
public RequestExternalResouce(Context context, String url, String body, OnTaskDoneListener onTaskDoneListener) {
this.mContext = context;
this.urlStr = url;
this.requestBody= body;
this.onTaskDoneListener = onTaskDoneListener;
}
#Override
protected String doInBackground(String... params) {
try {
URL mUrl = new URL(urlStr);
HttpURLConnection httpConnection = (HttpURLConnection) mUrl.openConnection();
httpConnection.setRequestMethod("POST");
httpConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
httpConnection.setUseCaches(false);
httpConnection.setAllowUserInteraction(false);
httpConnection.setConnectTimeout(1000000);
httpConnection.setReadTimeout(1000000);
httpConnection.setDoOutput(true);
DataOutputStream localDataOutputStream = new DataOutputStream(httpConnection.getOutputStream());
localDataOutputStream.writeBytes(requestBody.toString());
localDataOutputStream.flush();
localDataOutputStream.close();
int responseCode = httpConnection.getResponseCode();
httpConnection.connect();
BufferedReader br = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
if (responseCode == HttpURLConnection.HTTP_OK) {
return sb.toString();
}
} catch (IOException e) { e.printStackTrace();
} catch (Exception ex) { ex.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (onTaskDoneListener != null && s != null) {
onTaskDoneListener.onTaskDone(s);
} else
onTaskDoneListener.onError();
}
public interface OnTaskDoneListener {
void onTaskDone(String responseData);
void onError();
}
}

Java getter and setter issue

When setting a value in setData the value is OK in String returnDataTab1, but when getId() states it's null. Is the issue staring me in the face.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.widget.Toast;
public class BackgroundTask extends AsyncTask<String,Void,String>
{
Context context;
String dataResponse = "";
String returnDataTab1;
//getter
public String getId()
{
//The system out below shows a value of null although the setData method set it ok.
System.out.println("zzzzzzzzzzzzzzzzzzzzzzzzzzzzz : "+returnDataTab1);
return returnDataTab1;
}
public void setData(String newResult)
{
returnDataTab1=newResult;
System.out.println("zzzzzzzzzzzzzzzzzzzzzzzzzzzzz : "+returnDataTab1);
/// the returnDataTab value is set ok
}
BackgroundTask(Context ctx)
{
this.context = ctx;
}
#Override
protected String doInBackground(String... params)
{
String urlLogin = "";
String task = params[0];
String loginusername="";
String loginpassword="";
if (task.equals("login"))
{
urlLogin = "http://domain/LoginAndRegister-login.php";
loginusername = params[1];
loginpassword = params[2];
//
try
{
URL url = new URL(urlLogin);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
//send the driver number to the database
OutputStream outputStream = httpURLConnection.getOutputStream();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream,"UTF-8");
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
String myDatalogin = URLEncoder.encode("identifier_loginEmail","UTF-8")+"="+URLEncoder.encode(loginusername,"UTF-8")
+"&"+URLEncoder.encode("identifier_loginPassword","UTF-8")+"="+URLEncoder.encode(loginpassword,"UTF-8");
bufferedWriter.flush();
bufferedWriter.write(myDatalogin);
bufferedWriter.close();
outputStream.close();
//get response from the database
InputStream inputStream = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"UTF-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
//String dataResponse = "";
String inputLine = "";
while((inputLine = bufferedReader.readLine()) != null)
{
dataResponse += inputLine;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return dataResponse;
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}//end if statement
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Void... values)
{
super.onProgressUpdate(values);
}
/// gets value OK from background task
#Override
protected void onPostExecute(String result)
{
this.setData(result);
}
}
Would appreciate if you guys could take a look and point out the obvious mistake.
This is the code called from a tab
BackgroundTask backgroundTaskLogin = new BackgroundTask(Tab1Activity.this);
backgroundTaskLogin.execute(task,username,password);
String x;
x=backgroundTaskLogin.getId();
Toast.makeText(getApplicationContext(), "Data Response : "+x, Toast.LENGTH_SHORT).show();
The values are set from
protected void onPostExecute(String result)
{
this.setData(result);
// gets result value fine
}

How do I ensure that my list view element do not disappear when I change the orientation of my device?

I am building an app that displays details of a book you have searched. The problem is that every time I change the orientation of my device the list view elements disappear. I want help in how to make them not disappear. I have a feeling that I need to use a Loader but I have no idea in how to implement it. Here are my activities.
MainActivity :-
package com.example.visha.booklistingapp;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private BookAdapter mAdapter;
EditText searchtext;
ListView earthquakeListView;
TextView empty;
TextView authorcheck;
TextView titlecheck;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
earthquakeListView = (ListView) findViewById(R.id.listView);
mAdapter = new BookAdapter(this, new ArrayList<Book>());
earthquakeListView.setAdapter(mAdapter);
searchtext = (EditText) findViewById(R.id.editText);
empty = (TextView) findViewById(R.id.textView);
earthquakeListView.setEmptyView(empty);
}
public void searchclick(View view) {
ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
String parturl = searchtext.getText().toString();
parturl = parturl.replaceAll("\\s","");
StringBuilder urlbuilder = new StringBuilder();
urlbuilder.append(" https://www.googleapis.com/books/v1/volumes?q=");
urlbuilder.append(parturl);
urlbuilder.append("&maxResults=5");
String url = urlbuilder.toString();
BookAsyncTask task = new BookAsyncTask();
task.execute(url); }
else{
Toast.makeText(getApplicationContext(), "You are not connected to the internet",
Toast.LENGTH_LONG).show();
}
}
private class BookAsyncTask extends AsyncTask<String, Void, List<Book>> {
#Override
protected List<Book> doInBackground(String... urls) {
// Don't perform the request if there are no URLs, or the first URL is null
if (urls.length < 1 || urls[0] == null) {
return null;
}
List<Book> result = QueryUtils.fetchBookData(urls[0]);
return result;
}
#Override
protected void onPostExecute(List<Book> data) {
mAdapter.clear();
if (data != null && !data.isEmpty()) {
mAdapter.addAll(data);
}
}
}
}
QueryUtils :-
package com.example.visha.booklistingapp;
import android.text.TextUtils;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
/**
* Created by visha on 14-10-2016.
*/
public final class QueryUtils {
private static final String LOG_TAG = QueryUtils.class.getSimpleName();
private QueryUtils() {
}
public static List<Book> fetchBookData(String requestUrl) {
URL url = createUrl(requestUrl);
String jsonResponse = null;
try {
jsonResponse = makeHttpRequest(url);
} catch (IOException e) {
Log.e(LOG_TAG, "Problem making the HTTP request.", e);
}
List<Book> Books = extractFeatureFromJson(jsonResponse);
return Books;
}
private static URL createUrl(String stringUrl) {
URL url = null;
try {
url = new URL(stringUrl);
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Problem building the URL ", e);
}
return url;
}
private static String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";
if (url == null) {
return jsonResponse;
}
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
if (urlConnection.getResponseCode() == 200) {
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
} else {
Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());
}
} catch (IOException e) {
Log.e(LOG_TAG, "Problem retrieving the Book JSON results.", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (inputStream != null) {
inputStream.close();
}
}
return jsonResponse;
}
private static String readFromStream(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null) {
output.append(line);
line = reader.readLine();
}
}
return output.toString();
}
private static List<Book> extractFeatureFromJson(String BookJSON) {
if (TextUtils.isEmpty(BookJSON)) {
return null;
}
List<Book> Books = new ArrayList<>();
try {
JSONObject baseJsonResponse = new JSONObject(BookJSON);
JSONArray BookArray = baseJsonResponse.getJSONArray("items");
for (int i = 0; i < BookArray.length(); i++) {
JSONObject currentBook = BookArray.getJSONObject(i);
JSONObject properties = currentBook.getJSONObject("volumeInfo");
String author;
if(properties.has("authors")) {
author = properties.getString("authors");
}
else {
author = "";
}
String title = properties.getString("title");
Book Book = new Book(author, title);
Books.add(Book);
}
} catch (JSONException e) {
Log.e("QueryUtils", "Problem parsing the Book JSON results", e);
}
return Books;
}
}
You need to override onSaveInstanceState and onRestoreInstanceState methods of Activity Class.
In onSaveInstanceState, save the list data into the Bundle.
In onRestoreInstanceState, restore the list with the Bundle data and re-create the list adapter.
Cheers!!!
if you do not have a different layout for the activity landscape mode then simply putting android:configChanges="orientation|screenLayout|screenSize" will do the job for you.
Example:
<activity
android:name=".MainActivity"
android:configChanges="orientation|screenLayout|screenSize" />
and if you do have different layout for landscape mode the you need to override the savedInstanceState and save and restore the list accordingly in OnCreate

Android - get distance using google maps api and json

I could retreive data from web with this code:
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClick (View v){
new GetMethodDemo().execute("https://maps.googleapis.com/maps/api/directions/json?origin=Breclav&destination=Brno&sensor=false&units=metric&mode=driving");
}
public class GetMethodDemo extends AsyncTask<String , Void ,String> {
String server_response;
#Override
protected String doInBackground(String... strings) {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(strings[0]);
urlConnection = (HttpURLConnection) url.openConnection();
int responseCode = urlConnection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
server_response = readStream(urlConnection.getInputStream());
Log.v("CatalogClient", server_response);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.e("Response", "" + server_response);
}
}
private String readStream(InputStream in) {
BufferedReader reader = null;
StringBuffer response = new StringBuffer();
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
response.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response.toString();
} }
I am able to see in debug that I received data like in this link, but I found that I should use code below for selecting only distance from the data I received. Dont know how to combinate these codes together.. I would like to have in textView how far is the distance between two cities from url.
final JSONObject json = new JSONObject(response);
JSONArray routeArray = json.getJSONArray("routes");
JSONObject routes = routeArray.getJSONObject(0);
JSONArray newTempARr = routes.getJSONArray("legs");
JSONObject newDisTimeOb = newTempARr.getJSONObject(0);
JSONObject distOb = newDisTimeOb.getJSONObject("distance");
JSONObject timeOb = newDisTimeOb.getJSONObject("duration");
Log.i("Diatance :", distOb.getString("text"));
Log.i("Time :", timeOb.getString("text"));
I am not the author of these codes... Thank You

Categories