-2

I have been stuck for weeks.....for this problem I am using AsynTask to send data to php and recieve a name to print but it showed this error anyone to help ??

12-29 19:34:12.623: D/dalvikvm(799): GC_CONCURRENT freed 188K, 11% free 2629K/2948K, paused 25ms+61ms, total 218ms
12-29 19:34:13.282: D/gralloc_goldfish(799): Emulator without GPU emulation detected.
12-29 19:34:42.132: W/System.err(799): java.lang.NullPointerException
12-29 19:34:42.164: W/System.err(799):  at android.app.Activity.findViewById(Activity.java:1839)
12-29 19:34:42.164: W/System.err(799):  at com.example.myweb.MainActivity.afterEffect(MainActivity.java:64)
12-29 19:34:42.164: W/System.err(799):  at com.example.myweb.toPHP.onPreExecute(toPHP.java:47)
12-29 19:34:42.164: W/System.err(799):  at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
12-29 19:34:42.164: W/System.err(799):  at android.os.AsyncTask.execute(AsyncTask.java:534)
12-29 19:34:42.164: W/System.err(799):  at com.example.myweb.MainActivity$1.onClick(MainActivity.java:54)
12-29 19:34:42.172: W/System.err(799):  at android.view.View.performClick(View.java:4204)
12-29 19:34:42.172: W/System.err(799):  at android.view.View$PerformClick.run(View.java:17355)
12-29 19:34:42.172: W/System.err(799):  at android.os.Handler.handleCallback(Handler.java:725)
12-29 19:34:42.185: W/System.err(799):  at android.os.Handler.dispatchMessage(Handler.java:92)
12-29 19:34:42.185: W/System.err(799):  at android.os.Looper.loop(Looper.java:137)
12-29 19:34:42.192: W/System.err(799):  at android.app.ActivityThread.main(ActivityThread.java:5041)
12-29 19:34:42.212: W/System.err(799):  at java.lang.reflect.Method.invokeNative(Native Method)
12-29 19:34:42.212: W/System.err(799):  at java.lang.reflect.Method.invoke(Method.java:511)
12-29 19:34:42.212: W/System.err(799):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
12-29 19:34:42.222: W/System.err(799):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
12-29 19:34:42.222: W/System.err(799):  at dalvik.system.NativeStart.main(Native Method)

JSONParser.java

 package com.example.myweb;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";
    // constructor
    public JSONParser() {
    }
    public JSONObject getJSONFromUrl(String url, List params) {
        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "n");
            }
            is.close();
            json = sb.toString();
            Log.e("JSON", json);
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }
        // return JSON String
        return jObj;
    }
}

toPHP.java

 package com.example.myweb;

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


import org.apache.http.HttpEntity;
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.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

public class toPHP extends AsyncTask {

    MainActivity main = new MainActivity();
    private JSONParser jsonParser;
    String email,password;
    EditText emailBox;
    EditText passwordBox;
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        main.afterEffect("sending...");
        emailBox = (EditText) main.findViewById(R.id.email);
        passwordBox = (EditText) main.findViewById(R.id.password);
        email = emailBox.getText().toString();
        password = passwordBox.getText().toString();    
    }
    protected JSONObject doInBackground(String... args) {
        toPHP userFunction = new toPHP();
        JSONObject json = null;
        try {
            json = userFunction.getUserLoggedIn(email, password);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return json;        
     }


    public JSONObject getUserLoggedIn(String email,String password) throws ClientProtocolException, IOException, JSONException{
        JSONObject json = null;
        /*
        HttpClient client = new DefaultHttpClient();
        HttpPost  post = new HttpPost("http://localhost/testand.php");
        */
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("email", email));
        pairs.add(new BasicNameValuePair("password", password));
        //post.setEntity(new UrlEncodedFormEntity(pairs));
        //HttpResponse response = client.execute(post);
        //HttpEntity resEntity = response.getEntity();

        //if (resEntity != null) {

            //String responseStr = EntityUtils.toString(resEntity).trim();

            json = jsonParser.getJSONFromUrl("http://localhost/testand.php", pairs);



        //}     
        return json;
    }

    protected void onPostExecute(JSONObject json) throws JSONException {
        String myName = json.getString("name");
        String str = myName + ", Welcome to Socionet. :) ";
        main.afterEffect(str);
    }
    @Override
    protected Object doInBackground(Object... params) {
        // TODO Auto-generated method stub
        return null;
    }

}

MainActivity.java

package com.example.myweb;

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


import org.apache.http.HttpEntity;
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.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

public class MainActivity extends Activity {
    Button button;
    EditText emailBox;
    EditText passwordBox;
    String emailId;
    String passwordId;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) findViewById(R.id.login1);
        emailBox   = (EditText)findViewById(R.id.email);
        passwordBox   = (EditText)findViewById(R.id.password);

       button.setOnClickListener(new Button.OnClickListener()   {             
           public void onClick(View v)  {               
            try {
               new toPHP().execute();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();                    
            }               
           }  
         });
       }
    public void afterEffect(String str){

        TextView textV1 = (TextView)findViewById(R.id.textV1);
        textV1.setText(str);        

    }
}

UPDATE 1

new errors after @hasan83 's fixes

12-29 21:38:27.588: W/dalvikvm(1283): threadid=11: thread exiting with uncaught exception (group=0x40a71930)
12-29 21:38:27.748: E/AndroidRuntime(1283): FATAL EXCEPTION: AsyncTask #1
12-29 21:38:27.748: E/AndroidRuntime(1283): java.lang.RuntimeException: An error occured while executing doInBackground()
12-29 21:38:27.748: E/AndroidRuntime(1283):     at android.os.AsyncTask$3.done(AsyncTask.java:299)
12-29 21:38:27.748: E/AndroidRuntime(1283):     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
12-29 21:38:27.748: E/AndroidRuntime(1283):     at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
12-29 21:38:27.748: E/AndroidRuntime(1283):     at java.util.concurrent.FutureTask.run(FutureTask.java:239)
12-29 21:38:27.748: E/AndroidRuntime(1283):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
12-29 21:38:27.748: E/AndroidRuntime(1283):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
12-29 21:38:27.748: E/AndroidRuntime(1283):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
12-29 21:38:27.748: E/AndroidRuntime(1283):     at java.lang.Thread.run(Thread.java:856)
12-29 21:38:27.748: E/AndroidRuntime(1283): Caused by: java.lang.NullPointerException
12-29 21:38:27.748: E/AndroidRuntime(1283):     at com.example.myweb.toPHP.getUserLoggedIn(toPHP.java:99)
12-29 21:38:27.748: E/AndroidRuntime(1283):     at com.example.myweb.toPHP.doInBackground(toPHP.java:67)
12-29 21:38:27.748: E/AndroidRuntime(1283):     at com.example.myweb.toPHP.doInBackground(toPHP.java:1)
12-29 21:38:27.748: E/AndroidRuntime(1283):     at android.os.AsyncTask$2.call(AsyncTask.java:287)
12-29 21:38:27.748: E/AndroidRuntime(1283):     at java.util.concurrent.FutureTask.run(FutureTask.java:234)
12-29 21:38:27.748: E/AndroidRuntime(1283):     ... 4 more
Smri Tasya
  • 21
  • 2
  • 1
    possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – njzk2 Dec 29 '14 at 19:47

4 Answers4

1

You can't create a new MainActivity in your AsyncTask. When you are in your MainActivity, pass the activity to the constructor of the AsyncTask. You will be able to get and update your views in the onPreExecute() method.

public class toPHP extends AsyncTask {
    public toPHP(Activity activity) {
    }
}

And in your activity:

new toPHP(MainActivity.this).execute();
0

Add a constructor so that you can pass in the current MainActivity to your AsyncTask

public class toPHP extends AsyncTask {

    final MainActivity main;

    public toPHP(MainActivity main) {
        this.main = main;
    }
    ...

then call like so

 button.setOnClickListener(new Button.OnClickListener()   {             
       public void onClick(View v)  {               
        try {
           new toPHP(MainActivity.this).execute();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();                    
        }               
       }  
     });
   }
petey
  • 16,914
  • 6
  • 65
  • 97
0

Error says it's unable to find your TextView with id of R.id.textV1. Make sure it's available in the content view :R.layout.activity_main

But the main problem is why are you doing this MainActivity main = new MainActivity(), in your AsyncTask. It should be passed by reference from the actual Activity.

ZakiMak
  • 2,072
  • 2
  • 17
  • 26
0

Points:

  1. I don't see @Override keyword before onPostExecute and doInBackground methods.
  2. Move the code in onPreExecute to doInBackground.
  3. Send the main activity as a parameter for the AsynkTask execute method.
  4. Catch the activity on the do doInBackground.
  5. dont' declare an object of toPhp just call getUserLoggedIn. you are in the same class.

That's it.

new toPHP().execute(MainActivity.this);

@Override
protected Object doInBackground(Object... args) {

    main = (MainActivity) args[0];
    main.afterEffect("sending...");
    emailBox = (EditText) main.findViewById(R.id.email);
    passwordBox = (EditText) main.findViewById(R.id.password);
    email = emailBox.getText().toString();
    password = passwordBox.getText().toString();
    ..
}
hasan
  • 23,815
  • 10
  • 63
  • 101
  • number 4 is the first line in doInBackground method. – hasan Dec 29 '14 at 20:14
  • you're a marskmen dude! But what do i keep in `onPreExecute()` ? – Smri Tasya Dec 29 '14 at 20:15
  • the method that actually work in background and the one you need to start an http request is doInBackground. "logical name for method :)". onPreExecute work on main thread which freeze the UI. you should move the code in onPreExecute to doInBackground. – hasan Dec 29 '14 at 20:16
  • I believe you can't benefit from onPreExecute in your case. because you can only get main activity in doInBackground method. the parameters sent by execute method sent to doInBackground. not onPreExecute. – hasan Dec 29 '14 at 20:18
  • I updated one word in the answer. also don't forgot @Override keyword. – hasan Dec 29 '14 at 20:19
  • so theres no need of `onpreex` method ? – Smri Tasya Dec 29 '14 at 20:20
  • at least not in your case. – hasan Dec 29 '14 at 20:21
  • and when adding @override getting an error `method doInbackgr... of toPHP type must implement or override a supertype` @hasan83 – Smri Tasya Dec 29 '14 at 20:23
  • I created a github project once for someone asked how to use asynctask for an http request. you can check it out. https://github.com/hasanalbukhari/Android-Json-Parse-and-Structure it also show best practice where to do different things. as updating the UI and other things. check it out. – hasan Dec 29 '14 at 20:24
  • ok I think you are right. I do add @Override to my implementation because I use my own version of asynctask. got confused remove it. u can see it in the github project. – hasan Dec 29 '14 at 20:26
  • doInBackground wont call...its calling preExecute() @hasan83 – Smri Tasya Dec 29 '14 at 20:48
  • check the example here http://developer.android.com/reference/android/os/AsyncTask.html how you extend asynctask with parameter types. its also exists in the git hub project example. – hasan Dec 29 '14 at 21:12
  • public class HttpClientThread extends AsyncTask – hasan Dec 29 '14 at 21:13
  • send it to my email. hasanal_bukhari@hotmail – hasan Dec 29 '14 at 21:36
  • man it's wrong to just keep updating the question for new problems. it's not a forum. you must ask new question. what if one user solved a problem and other one solved another problem. who got the right answer. send me your project I will fix it. – hasan Dec 29 '14 at 21:46