Variable has not accessed from inner class - java

I have inner class which run code in UI thread and I need to pass variable to run() method.
I try to pass final res without array but I've got an error that it's necessary to use array res[0].
In this case I need to initialize res[] because it throws NullPointerException.
Are there any other way to pass variable into inner class?
private String sendRequest(String url, String... data) {
final Connection.Response[] res = {};
...
try {
final Connection connection = Jsoup.connect(url)
.method(Connection.Method.POST)
.cookies(cookies)
.timeout(30000)
.ignoreContentType(true);
if (data != null) {
connection.data(data);
}
((Activity) con).runOnUiThread(new Runnable() {
#Override
public void run() {
try {
res[0] = connection.execute();
} catch (IOException e) {
e.printStackTrace();
}
}
});
result = Jsoup.parse(res[0].parse().outerHtml(), "UTF-8").text();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}

res[] is defined as an empty array (no locations), then you try to assign to something to location 0 in res[], there is no location 0 because it needs to be given a size...
final Connection.Response[] res = new Connection.Response[requiredArraySize];
In your case, requiredArraySize is probably 1.

Related

Getting null value of Global variable in java class?

Here is my Code:
public class ServerCall {
Context context;
public int cartCount;
public ServerCall(Context context){
this.context=context;
}
public Integer addCartItem(RequestObject requestObject) {
new AddToCartList().execute(requestObject);
Log.d("count",String.valueOf(cartCount));
return cartCount;
}
public class AddToCartList extends AsyncTask<RequestObject, Void, JSONObject> {
#Override
protected JSONObject doInBackground(RequestObject... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(arg0[0], ServiceHandler.POST);
// List<Products> result = new ArrayList<Products>();
Log.d("Response: ", "> " + jsonStr);
JSONObject product = new JSONObject();
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
product = jsonObj.getJSONObject("rsBody");
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return product;
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
try {
if (result != null) {
String status = result.getString("status");
int totalCartItem = result.getInt("totalCartItem");
/* cartHelper = new CartHelper();
cartHelper.setStatus(status);
cartHelper.setTotalCartItem(totalCartItem);*/
cartCount=totalCartItem;
Log.d("status",status);
Log.d("totalCartItem",String.valueOf(cartCount));
Toast.makeText(context, status, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
return;
}
}
}
We didn't get value of global variable cartCount which I set inside AddToCartList class and try to get its value from addCartItem() function from where AddToCartList is called but we get null value.
I think that the main problem in your solution is the fact that you're trying to edit ServerCall variable from an Inner class, this would work only if cartCount is static, and I suggest you wait for your task to be finished as some people have already mentioned, using the get method new AddToCartList().execute().get()
The problem is, ServerCall and AddToCartList are not the same class, so you must first get a reference to the servercall in addtocartlit, then reference the cartCount using your reference to the servercall instance, like call.cartCount, instead of cartcount, unless its an inner class which it does not appear to be.
Secondly, you must save a reference to the addtocartlist asynctask inside addCartItem() ,then call its .get() method after starting it, this will ensure it finishes before you try to log the new value.

Getting: "java.lang.NullPointerException" but I know object is instantiated in AsyncTask

I am attempting to pass a string I got in an Asynchronous task class back in to my main activity, but when I pass the string result (which I know isn't null because logging the string right before passing it to the interface outputs what it should), I get a nullPointerException that says I can't pass a null object to the interface method.
Here is the AsyncTask class,
public class APICalls extends AsyncTask<String,Void, String> {
public AsyncResponse delegate;
protected String doInBackground(String... zipcodes){
String zipcode = zipcodes[0];
String apikey = "6562c36e87ba41f6bc887104d1e82eb8";
String baseURL = "https://congress.api.sunlightfoundation.com";
String zipCodeAddition = "/legislators/locate?apikey="+apikey + "&zip=" + zipcode;
String url = baseURL + zipCodeAddition;
String results = "";
URL apiurl = null;
try {
apiurl = new URL(url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
HttpsURLConnection urlConnection = null;
try {
urlConnection = (HttpsURLConnection) apiurl.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
int data = in.read();
while(data != -1){
results += String.valueOf((char) data);
data = in.read();
}
in.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
urlConnection.disconnect();
}
return results;
}
protected void onPostExecute(String result){
String results = result;
try {
delegate.processFinish(results);
} catch (IOException e) {
e.printStackTrace();
}
}
}
The error occurs in the line delegate.processFinish(results);. When I log the results string it is not null. The interface is:
public interface AsyncResponse {
void processFinish(String output) throws IOException;
}
Then in the main activity I implement the interface and have the method:
public void processFinish(String output) throws IOException {
Log.v("++++++++", output);
}
You get NPE not because output is null, but because delegate is. You never initialize it.

Unhandled exception type URISyntaxException when trying to make links clickable in JTable

The aim is to make the link clickable in jtable so that when user clicks on the link the desired page gets opened in the browser. One of the items fetched from database is link and my attempt is to make it active and clickable. I get the error as
Unhandled exception type URISyntaxException
For the line in my code:
final URI uri = new URI("http://www.roseindia.net");
And even if i put it in try catch block, the error doesn't seem to resolve. Rather on surrounding in a try-catch block, I get the error as
Cannot refer to a non-final variable uri inside an inner class defined in a different method
So what could be the possible solution and fix?
public class JTableButtonMouseListener extends MouseAdapter
{
private final JTable table;
public JTableButtonMouseListener(JTable table)
{
this.table = table;
}
public void mouseClicked(MouseEvent e) {
counter=0;
// System.out.println("***************************************************************");
System.out.println("counter value="+counter++);
//System.out.println("/////////////////////////////////////////////////////////////////////");
int column = table.getColumnModel().getColumnIndexAtX(e.getX());
int row = e.getY()/table.getRowHeight();
if (row < table.getRowCount() && row >= 0 && column < table.getColumnCount() && column >= 0) {
Object value = table.getValueAt(row, column);
// System.out.println("row clicked="+row);
//System.out.println("column clicked="+column);
System.out.println("object value="+value);
System.out.println(".............................................................");
/* public void getsecname(String s)
{
String ss=s;
}*/
if(table.getValueAt(row, 4)!=null)
{
Object ob = table.getValueAt(row, 4);
String link_string=ob.toString();
// final URI uri = null;
// URI uri;
try{
final URI uri = new URI("http://www.roseindia.net");
}
catch (URISyntaxException e1)
{
e1.printStackTrace();
}
System.out.println(".....................");
((AbstractButton) ob).addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
try {
desktop.browse(uri);
// button.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
// desktop.setCursor(new Cursor(Cursor.HAND_CURSOR));
} catch (Exception ex) {
}
} else {
}
}
});
}
// String link_string=ob.toString();
//ob.setClickable(true);
if(value==null)
{
Object v=table.getValueAt(row, 1);
//System.out.println("--------------------------------------------");
s = v.toString();
jmenu_frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
jmenu_frame.setContentPane(new ListModelExample(s));
jmenu_frame.setSize(260, 200);
jmenu_frame.setVisible(true);
jmenu_frame.setLocationRelativeTo(null);
//it ends here
}
if (value instanceof JButton) {
((JButton)value).doClick();
}
}
}
}
You can not use non-final variable inside your inner class. Discussion.
if(table.getValueAt(row, 4)!=null)
{
Object ob = table.getValueAt(row, 4);
String link_string=ob.toString();
try {
final URI uri = new URI("http://www.roseindia.net");
System.out.println(".....................");
((AbstractButton) ob).addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
try {
desktop.browse(uri);
//button.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
// desktop.setCursor(new Cursor(Cursor.HAND_CURSOR));
} catch (Exception ex) {
}
}
}
});
} catch (URISyntaxException e1) {
e1.printStackTrace();
}
}
What is telling you is that you need a try catch block to handle a URISyntaxException:
final URI;
try{
uri = new URI("http://www.roseindia.net");
} catch (URISyntaxException e) {
e.printStackTrace();
}
To solve uri cannot be resolved to a variable You could instead of using try catch, add a throws URISyntaxException to the method in which uri is declared. But I do not think that is a good practice. Maybe it works in your case.

Trying to return with a variable which is cannot be resolved as variable

I'm new im Java, and im trying to return with a defined string variable at the end of the function, but eclipse keeps saying that it's cannot be resolved to a variable, and wants me to define it. Probably it's because im define the variable within the Try{} brackets, but how else could i do it?
public class readtextfile extends AsyncTask<String, Integer, String>{
private TextView description;
public readtextfile(TextView descriptionTextView){
this.description = descriptionTextView;
}
#Override
protected String doInBackground(String... params) {
try {
URL url = new URL("http://example.com/description1.txt");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String line = null;
String result = "";
while ((line = in.readLine()) != null) {
//get lines
result+=line;
}
in.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
protected void onProgressUpdate() {
//called when the background task makes any progress
}
protected void onPreExecute() {
//called before doInBackground() is started
}
#Override
protected void onPostExecute(String result) {
this.description.setText(result);
}
}
Move the local variable declaration
String result = "";
to before the try block. If you define a variable within a block it's not available outside that block.
Alternatively you could move return result; to the end of the try block, but then you'd have to add another return statement at the end of the method, for the cases where an exception was thrown and got caught.
Or you could get rid of the try-block, move the exception-handling to elsewhere, and let any exceptions get thrown.
URL url = null;
String result = "";
Then inside your try, catch block.
try {
url = ....;
.
.
result = ....;
Declare the variable outside the try block.

modify method argument or return in java

I have seen this method in android source code.
protected LocaleConfiguration doInBackground(Void... unused) {
LocaleConfiguration localeConfiguration = new LocaleConfiguration();
readConfiguration(Launcher.this, localeConfiguration);
return localeConfiguration;
}
private static void readConfiguration(Context context, LocaleConfiguration configuration) {
DataInputStream in = null;
try {
in = new DataInputStream(context.openFileInput(PREFERENCES));
configuration.locale = in.readUTF();
configuration.mcc = in.readInt();
configuration.mnc = in.readInt();
} catch (FileNotFoundException e) {
// Ignore
} catch (IOException e) {
// Ignore
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// Ignore
}
}
}
}
why not something like this
private static LocaleConfiguration readConfiguration(Context context) {
LocaleConfiguration configuration = new LocaleConfiguration();
DataInputStream in = null;
try {
in = new DataInputStream(context.openFileInput(PREFERENCES));
configuration.locale = in.readUTF();
configuration.mcc = in.readInt();
configuration.mnc = in.readInt();
} catch (FileNotFoundException e) {
// Ignore
} catch (IOException e) {
// Ignore
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// Ignore
}
}
}
return configuration;
}
what is the advantage of modifying argument instead of returning new value
The advantage of modifying an argument instead of returning a new instance is that you put control of instantiation in the hands of the calling code - i.e. you allow it to re-use an existing instance.
The 'modifying argument' approach allows you to initialise an object using several such methods. e.g.
LocaleConfiguration localeConfiguration = new LocaleConfiguration();
readConfiguration(Launcher.this, localeConfiguration);
readSomeOtherConfiguration(Launcher.this, localeConfiguration);
return localeConfiguration;
Arguably you could do the same thing by returning the same instance as was passed in as a parameter, but I personally think that's asking for trouble.
Another possible reason might be if the cost of instantiation was high, you might want to recycle an old object. This doesn't appear to be the case with the code you present though, and it's an optimisation so only think about doing this if absolutely necessary!
Personally I would tend to take the 'return a new instance' approach unless there's a specific reason not to. I think it's simpler and decreases the likelihood of subtle errors in the calling code.

Categories

Resources