2

I have activity and class. In activity I do HTTP GET request (HttpClass.java), then in GetMethod.java I do Asynctask. In onPostExecute function I want to return to activity and parse data with JSON. It works, but when I try to create layout with textview and button programmaticaly for every item of data array, it throws NullPointerException.

Code:

HttpClass.java

@Override
protected void onCreate (Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.httplayout);
    cont = this;
    ll = (LinearLayout) findViewById(R.id.llHttp);
    sv = (ScrollView) findViewById(R.id.svHttp);
    //httptv = (TextView) findViewById(R.id.tvHttp);
    font = Typeface.createFromAsset(getAssets(), "fontawesome-webfont.ttf");
    font2 = Typeface.createFromAsset(getAssets(), "OpenSans-Regular.ttf");
    GetMethod test = new GetMethod();
    test.execute(new String[] {"url"}); 
}

public void getResultData(String result) throws Exception {
    // TODO Auto-generated method stub
    resultdata = result;

    JSONObject jObject;
    jObject = new JSONObject(resultdata);

    //JSONObject object = jObject.getJSONObject("pharms");
    JSONArray jArray = jObject.getJSONArray("pharms");

for (int i = 0; i < jArray.length(); i++) {
    name = jArray.getJSONObject(i).getString("name").toString();
    phone = jArray.getJSONObject(i).getString("phone").toString();
    latitude = jArray.getJSONObject(i).getString("latitude").toString();
    longitude = jArray.getJSONObject(i).getString("longitude").toString();
    address = jArray.getJSONObject(i).getString("address").toString();

    RelativeLayout ll2 = new RelativeLayout(cont);
    //ll2.setOrientation(Orientation.ho)

    Button call = new Button(cont);
    call.setId(i+1);
    call.setClickable(true);
    call.setTypeface(font);
    call.setText(R.string.call);
    call.setTextColor(Color.rgb(0, 176, 128));
    call.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
    RelativeLayout.LayoutParams params1 = (RelativeLayout.LayoutParams)call.getLayoutParams();
    params1.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
    params1.setMargins(0, 25, 0, 0);
    call.setLayoutParams(params1);
    call.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
              Intent callIntent = new Intent(Intent.ACTION_CALL);
                callIntent.setData(Uri.parse("tel:123456789"));
                startActivity(callIntent);
        }
    });
    ll2.addView(call);
    TextView tv = new TextView(cont);
    tv.setId(i+1);
    tv.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
    RelativeLayout.LayoutParams params3 = (RelativeLayout.LayoutParams)tv.getLayoutParams();
    params3.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
    params3.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
    params3.setMargins(10, 25, 0, 0);
    tv.setLayoutParams(params3);
    tv.setText(name + "\n" + phone);
    tv.setTextSize(20);
    tv.setTypeface(font2);
    tv.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    });
    ll2.addView(tv);

    ll.addView(ll2);
}
}

And this is GetMethod.java class

@Override
protected String doInBackground(String... urls){
    BufferedReader in = null;
    String data = null;
      for (String url : urls) {
          HttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet(url);
        try {
            HttpResponse response = client.execute(request);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer sb = new StringBuffer("");
            String l = "";
            String nl = System.getProperty("line.separator");
            while ((l = in.readLine()) != null) {
                sb.append(l + nl);
            }
            in.close();
            data = sb.toString();               
            return data;
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
      return data;
}

 @Override
    protected void onPostExecute(String result) {
        HttpClass hc = new HttpClass();
        try {
            hc.getResultData(result);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

EDIT: LogCat log

    09-17 01:35:53.955: W/System.err(18700):          java.lang.NullPointerException 
    09-17 01:35:53.980:    W/System.err(18700):     at    android.view.ViewConfiguration.get(ViewConfiguration.java:332) 
    09-17    01:35:53.980: W/System.err(18700):     at    android.view.View.<init>(View.java:3322) 
    09-17 01:35:53.980:    W/System.err(18700):     at    android.view.ViewGroup.<init>(ViewGroup.java:421) 
    09-17 01:35:53.980:    W/System.err(18700):     at    android.widget.RelativeLayout.<init>(RelativeLayout.java:180) 
    09-17    01:35:53.980: W/System.err(18700):     at    com.example.behealthy.HttpClass.getResultData(HttpClass.java:77)
    09-17 01:35:53.980: W/System.err(18700):    at    com.example.behealthy.GetMethod.onPostExecute(GetMethod.java:44)
    09-17 01:35:53.980: W/System.err(18700):    at    com.example.behealthy.GetMethod.onPostExecute(GetMethod.java:1) 
    09-17    01:35:53.980: W/System.err(18700):     at    android.os.AsyncTask.finish(AsyncTask.java:631) 
    09-17 01:35:53.980:    W/System.err(18700):     at    android.os.AsyncTask.access$600(AsyncTask.java:177) 
    09-17    01:35:53.980: W/System.err(18700):     at    android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
    09-17 01:35:53.980: W/System.err(18700):    at    android.os.Handler.dispatchMessage(Handler.java:99) 
    09-17    01:35:53.980: W/System.err(18700):     at    android.os.Looper.loop(Looper.java:137) 
    09-17 01:35:53.980:    W/System.err(18700):     at    android.app.ActivityThread.main(ActivityThread.java:4898) 
    09-17    01:35:53.985: W/System.err(18700):     at    java.lang.reflect.Method.invokeNative(Native Method) 
    09-17    01:35:53.985: W/System.err(18700):     at    java.lang.reflect.Method.invoke(Method.java:511) 
    09-17 01:35:53.985:    W/System.err(18700):     at    com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
    09-17 01:35:53.985: W/System.err(18700):    at    com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773) 
    09-17    01:35:53.985: W/System.err(18700):     at    dalvik.system.NativeStart.main(Native Method)
codeMagic
  • 44,549
  • 13
  • 77
  • 93
Askar Zaitov
  • 283
  • 1
  • 6
  • 15

1 Answers1

0

Instantiating an Activity like this is wrong which is why you get the NPE

  HttpClass hc = new HttpClass();
    try {
        hc.getResultData(result);

This is obviously a separate class so what you want to do is create an interface to give a callback when the task has finished.

This answer gives an example of using an interface with your AsyncTask.

If it were an inner class of your Activity then you could just call the function directly from onPostExecute() but if you need it to be a separate file then you will want to follow the example in the link.

Community
  • 1
  • 1
codeMagic
  • 44,549
  • 13
  • 77
  • 93
  • It works, thanks. But there is another problem. Function call.onClick isn't called. Can you help me? Or should I start new topic? – Askar Zaitov Sep 16 '13 at 23:59
  • 1
    Hmmm...not exactly sure off-hand. You have put a break point in there to make sure it doesn't enter? I'm not sure if you can do it that way or if you need to set the `onClick()` by doing `call.setOnClickListener(this);` then put `onClick()` outside of the method. – codeMagic Sep 17 '13 at 00:05
  • Such a simple decision) Putting onClick() outside is working. Thanks! – Askar Zaitov Sep 17 '13 at 00:13
  • You're welcome...glad its working and we both learned something. That's the magic of SO :) – codeMagic Sep 17 '13 at 00:18