0

so I am making app and I need app to get list of queries from internet http://www.arleitiss.netne.net/DBindex.php?action=fetchTrans and execute them. I did it, it shows no errors when testing on phone, but it throws nullpointer on AVD.

package com.example.droid;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.content.Context;
import android.util.Log;

public class OnlineSync {
    Context context;
    public OnlineSync(Context context){
        this.context = context;
    }
    public boolean AddUser(String username, String pass, String name, String city, String country, String age){
        HttpClient http = new DefaultHttpClient();
        HttpPost httpp = new HttpPost("http://www.arleitiss.netne.net/DBindex.php");
        boolean result = false;
        try{
            List<NameValuePair> nvp = new ArrayList<NameValuePair>(6);
            nvp.add(new BasicNameValuePair("action", "adduser"));
            nvp.add(new BasicNameValuePair("username", username));
            nvp.add(new BasicNameValuePair("password", pass));
            nvp.add(new BasicNameValuePair("name", name));
            nvp.add(new BasicNameValuePair("city", city));
            nvp.add(new BasicNameValuePair("country", country));
            nvp.add(new BasicNameValuePair("age", String.valueOf(age)));
            httpp.setEntity(new UrlEncodedFormEntity(nvp));

            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            String response = http.execute(httpp, responseHandler);
            Log.d("RESPONSE", response);
            if(response.toString().equals("ERROR1")){
                result = true;
            }
            else if(response.toString().equals("ERROR-1")){
                result = false;
            }

        }
        catch(ClientProtocolException e){result = false;}
        catch(IOException e){result = false;}
        return result;
    }

    public String[] SyncTrans(){
    BufferedReader in = null;
    String data = null;
    try{
    HttpClient client = new DefaultHttpClient();
    URI website = new URI("http://www.arleitiss.netne.net/DBindex.php?action=fetchTrans");
    HttpGet request = new HttpGet();
    request.setURI(website);
    HttpResponse response = client.execute(request);
    in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    StringBuffer sb = new StringBuffer("");
    String l = "";
    String nl = System.getProperty("line.seperator");
    while(( l = in.readLine()) != null){
        sb.append(l + nl);
    }
    in.close();
    data = sb.toString();
    String arr[] = data.split("<br>");
    return arr;
    }
    catch(Exception e){}
    return null;
    }
    public void Exec(){
    DbCon dc = new DbCon(this.context);
    String queries[] = SyncTrans();
    for(int a = 0; a < queries.length-1; a++){
        dc.ExecQuery(queries[a]);
        Log.d("TAGG",queries[a].toString());
    }

    }

}

and in database I have simple function:

public void ExecQuery(String query){
        DbCon.this.open();
        database.rawQuery(query, null);
        DbCon.this.close();
    }

Help?

LogCat:

04-22 02:36:42.648: E/AndroidRuntime(5983): FATAL EXCEPTION: main 04-22 02:36:42.648: E/AndroidRuntime(5983): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.droid/com.example.droid.Incomes_act}: java.lang.NullPointerException 04-22 02:36:42.648: E/AndroidRuntime(5983): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180) 04-22 02:36:42.648: E/AndroidRuntime(5983): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230) 04-22 02:36:42.648: E/AndroidRuntime(5983): at android.app.ActivityThread.access$600(ActivityThread.java:141) 04-22 02:36:42.648: E/AndroidRuntime(5983): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234) 04-22 02:36:42.648: E/AndroidRuntime(5983): at android.os.Handler.dispatchMessage(Handler.java:99) 04-22 02:36:42.648: E/AndroidRuntime(5983): at android.os.Looper.loop(Looper.java:137) 04-22 02:36:42.648: E/AndroidRuntime(5983): at android.app.ActivityThread.main(ActivityThread.java:5039) 04-22 02:36:42.648: E/AndroidRuntime(5983): at java.lang.reflect.Method.invokeNative(Native Method) 04-22 02:36:42.648: E/AndroidRuntime(5983): at java.lang.reflect.Method.invoke(Method.java:511) 04-22 02:36:42.648: E/AndroidRuntime(5983): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 04-22 02:36:42.648: E/AndroidRuntime(5983): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 04-22 02:36:42.648: E/AndroidRuntime(5983): at dalvik.system.NativeStart.main(Native Method) 04-22 02:36:42.648: E/AndroidRuntime(5983): Caused by: java.lang.NullPointerException 04-22 02:36:42.648: E/AndroidRuntime(5983): at com.example.droid.OnlineSync.Exec(OnlineSync.java:89) 04-22 02:36:42.648: E/AndroidRuntime(5983): at com.example.droid.Incomes_act.onCreate(Incomes_act.java:88) 04-22 02:36:42.648: E/AndroidRuntime(5983): at android.app.Activity.performCreate(Activity.java:5104) 04-22 02:36:42.648: E/AndroidRuntime(5983): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080) 04-22 02:36:42.648: E/AndroidRuntime(5983): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144) 04-22 02:36:42.648: E/AndroidRuntime(5983): ... 11 more

another logcat log #2:

04-22 13:55:48.304: E/AndroidRuntime(933): FATAL EXCEPTION: main 04-22 13:55:48.304: E/AndroidRuntime(933): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.droid/com.example.droid.Incomes_act}: java.lang.NullPointerException 04-22 13:55:48.304: E/AndroidRuntime(933): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059) 04-22 13:55:48.304: E/AndroidRuntime(933): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084) 04-22 13:55:48.304: E/AndroidRuntime(933): at android.app.ActivityThread.access$600(ActivityThread.java:130) 04-22 13:55:48.304: E/AndroidRuntime(933): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195) 04-22 13:55:48.304: E/AndroidRuntime(933): at android.os.Handler.dispatchMessage(Handler.java:99) 04-22 13:55:48.304: E/AndroidRuntime(933): at android.os.Looper.loop(Looper.java:137) 04-22 13:55:48.304: E/AndroidRuntime(933): at android.app.ActivityThread.main(ActivityThread.java:4745) 04-22 13:55:48.304: E/AndroidRuntime(933): at java.lang.reflect.Method.invokeNative(Native Method) 04-22 13:55:48.304: E/AndroidRuntime(933): at java.lang.reflect.Method.invoke(Method.java:511) 04-22 13:55:48.304: E/AndroidRuntime(933): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 04-22 13:55:48.304: E/AndroidRuntime(933): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 04-22 13:55:48.304: E/AndroidRuntime(933): at dalvik.system.NativeStart.main(Native Method) 04-22 13:55:48.304: E/AndroidRuntime(933): Caused by: java.lang.NullPointerException 04-22 13:55:48.304: E/AndroidRuntime(933): at com.example.droid.OnlineSync.Exec(OnlineSync.java:92) 04-22 13:55:48.304: E/AndroidRuntime(933): at com.example.droid.Incomes_act.onCreate(Incomes_act.java:88) 04-22 13:55:48.304: E/AndroidRuntime(933): at android.app.Activity.performCreate(Activity.java:5008) 04-22 13:55:48.304: E/AndroidRuntime(933): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079) 04-22 13:55:48.304: E/AndroidRuntime(933): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)

created thread:

String arr[];
Thread trd = new Thread(new Runnable(){
      @Override
      public void run(){

                BufferedReader in = null;
                String data = null;
                try{
                final HttpClient client = new DefaultHttpClient();
                URI website = new URI("http://www.arleitiss.netne.net/DBindex.php?action=fetchTrans");
                final HttpGet request = new HttpGet();
                request.setURI(website);

                HttpResponse response = client.execute(request);
                in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                StringBuffer sb = new StringBuffer("");
                String l = "";
                String nl = System.getProperty("line.seperator");
                while(( l = in.readLine()) != null){
                    sb.append(l + nl);
                }
                in.close();

                data = sb.toString();
                String arr2[] = data.split("<br>");
                arr = arr2;
                }
                catch(Exception e){ 
                e.printStackTrace();
                return; 
                }

      }
    });
arleitiss
  • 107
  • 2
  • 13
  • updated, logcat posted in main question. Any ideas? – arleitiss Apr 22 '13 at 10:18
  • Probably some error occurred on SyncTrans, and since it handles every error and returns just null, accessing "queries.length" causes a null pointer exception. You have to test if "queries" is null if you return null at some point, so you don't end up with NullPointerExeceptions at any point. Also, probably printing the stacktrace on exception instead of just returning null will help a lot to see the actual problem. – Aitor Calderon Apr 22 '13 at 10:32
  • What do you mean by test queries? – arleitiss Apr 22 '13 at 12:39
  • On SyncTrans, change this catch(Exception e){} into this `catch(Exception e){ e.printStackTrace; return null; }`. And after `String queries[] = SyncTrans();`, test if queries is null: `if(queries== null) return;` This will avoid NullPointerException, and you will have to look into LogCat if any error occurred at SyncTrans. – Aitor Calderon Apr 22 '13 at 13:19
  • I tried running the changes, if I add if(queries==null) return; it didnt' show anything even any errors. If I removed it it gave me: – arleitiss Apr 22 '13 at 13:57
  • check logcat #2 in main post. – arleitiss Apr 22 '13 at 13:59
  • Take a look at my answer, also, have you tried the `e.printStackTrace();`at SyncTrans catch? (sorry for the missing parenthesis on my other comment) – Aitor Calderon Apr 22 '13 at 14:01

1 Answers1

0

What version of Android is the Phone running?, and what version is AVD running?

On Android Honeycomb and higher, you get an exception when you try to make network operation on the main thread (more on this here: Android http connection exception). If this is your case, you should perform network operations on a separate thread. Your phone probably is not complaining because its Android < 3.0 (maybe 2.3?) which lets you perform network operations on the main thread.

This may be the reason of your Null Pointer Exception because in that case, SyncTrans is failing to execute on AVD. As you silently catch the exceptions at this function, and return null if it fails, a NullPointerException is thrown, because after executing SyncTrans, your are accessing a property of it's returning value at for(int a = 0; a < queries.length-1; a++). A queries is null if SyncTrans fails, you will get the NullPointerException thrown trying to access it's length.

I hope this clarifies your questions.

EDIT: NO errors about this behavior are found at your code, because you are in fact hiding them doing this:

try{
    //Any code here
}
catch(Exception e){}

This is generally a bad practice, as you just silently catch the error without doing anything about it. If you change to this for example:

try{
    //Any code
}
catch(Exception e){
e.printStackTrace();
}

You will see in the Logcat a stack trace with your error.

Community
  • 1
  • 1
Aitor Calderon
  • 763
  • 6
  • 16
  • Phone version is 2.3.7 and AVD is 4.1.1 – arleitiss Apr 22 '13 at 14:00
  • But how come phone shows no errors then? I mean it looks like it goes through all process but actual queries are not executed ( I checked) – arleitiss Apr 22 '13 at 14:01
  • because you actually do an empty try catch, so no error is shown – Aitor Calderon Apr 22 '13 at 14:02
  • So you are saying one of my possible solutions is to run new thread for http request? – arleitiss Apr 22 '13 at 14:21
  • Better yes, in fact, it will help your app not to look as it is "hang" while time consuming operations such as HTTP requests are performed. Less recommended but a workaround, is change the target API to level 8 or 9 (2.2 or 2.3) depending on your needs. But as I said before, I don't recommend this. – Aitor Calderon Apr 22 '13 at 14:28
  • I've just added new piece of code, I wrapped it into run (new thread) i never worked with threads before so I am sure it doesn't work right. Still when I try accessing arr[] now, it shows exactly same error, nothing changed. – arleitiss Apr 22 '13 at 15:06
  • When do you try to use `arr`variable? Do you even start the Thread at any point? I really encourage you to understand android Threads and workers, and how to use them to fill UI elements with information retrieved by them. Anyways, I'm quiet sure the problem you were having was because of what I explained here. – Aitor Calderon Apr 22 '13 at 16:30