1

i'm completely new on android and this is my first project. I'm trying to make an android program that takes input from the user and perform some operations on mysql database, I ran the program but I got these errors:

    java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
        at com.example.nada.mysqldemo.MainActivity.viewResultMessage(MainActivity.java:89)
        at com.example.nada.mysqldemo.UserServiceAPI.onPostExecute(UserServiceAPI.java:83)
        at android.os.AsyncTask.finish(AsyncTask.java:632)
        at android.os.AsyncTask.access$600(AsyncTask.java:177)
        at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5221)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

can anyone tell me where is the error and how to fix it please? i'm attaching my code here: mainactivity.java

    import android.app.Activity;
    import android.app.ProgressDialog;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.EditText;
    import android.widget.Toast;

    public class MainActivity extends Activity {
    private EditText idEditText, nameEditText;
    private ProgressDialog loadingDialog;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    idEditText = (EditText) findViewById(R.id.et_id);
    nameEditText = (EditText) findViewById(R.id.et_name);

    loadingDialog = new ProgressDialog(this);
    loadingDialog.setCancelable(false);
    loadingDialog.setCanceledOnTouchOutside(false);
    loadingDialog.setMessage("Please wait...");
}

public void selectOneButtonAction(View v) {
    checkId();
    loadingDialog.show();
    new UserServiceAPI(this, UserServiceAPI.SELECT_ONE).execute(idEditText
            .getText().toString().trim(), "");
}

public void selectAllButtonAction(View v) {
    loadingDialog.show();
    new UserServiceAPI(this, UserServiceAPI.SELECT_ONE).execute("", "");
}

public void insertButtonAction(View v) {
    checkName();
    loadingDialog.show();
    new UserServiceAPI(this, UserServiceAPI.SELECT_ONE).execute("",
            nameEditText.getText().toString().trim());
}

public void deleteButtonAction(View v) {
    checkId();
    loadingDialog.show();
    new UserServiceAPI(this, UserServiceAPI.SELECT_ONE).execute(idEditText
            .getText().toString().trim(), "");
}

public void updateButtonAction(View v) {
    checkId();
    checkName();
    loadingDialog.show();
    new UserServiceAPI(this, UserServiceAPI.SELECT_ONE).execute(idEditText
            .getText().toString().trim(), nameEditText.getText().toString()
            .trim());
}

private void checkId() {
    if (idEditText.getText().toString().trim().length() == 0) {
        showToast("Missing id");
        return;
    }
}

private void checkName() {
    if (nameEditText.getText().toString().trim().length() == 0) {
        showToast("Missing name");
        return;
    }
}

private void showToast(String text) {
    Toast.makeText(this, text, Toast.LENGTH_LONG).show();
}

public void viewResultMessage(Object result) {
    if (loadingDialog.isShowing())
        loadingDialog.dismiss();
    showToast(result.toString());
}

    }

UserServiceAPI

    import java.net.SocketException;
    import java.net.SocketTimeoutException;
    import java.util.ArrayList;
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    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.JSONArray;
    import org.json.JSONObject;
    import android.os.AsyncTask;
    import android.util.Log;
    public class UserServiceAPI extends AsyncTask<String, Integer, Object> {
    public static final String INSERT = "insert";
    public static final String UPDATE = "update";
    public static final String DELETE = "delete";
    public static final String SELECT_ONE = "selectone";
    public static final String SELECT_ALL = "selectall";
    private String action;
    private MainActivity activity;
    //private String url = "http://192.168.1.100/mysql_android/user_operations.php";
private String url = "http://10.0.2.2/mysql_android/user_operations.php";

public UserServiceAPI(MainActivity activity, String action) {
    this.action = action;
    this.activity = activity;
}

@Override
protected Object doInBackground(String... params) {
    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("action", action));
    nameValuePairs.add(new BasicNameValuePair("id", params[0]));
    nameValuePairs.add(new BasicNameValuePair("name", params[1]));
    String connRs = connect(url, nameValuePairs);
    try {
        if (action.equals(INSERT) || action.equals(UPDATE)
                || action.equals(DELETE)) {
            JSONObject jsonObject = new JSONObject(connRs);
            return jsonObject.getString("message");
        } else if (action.equals(SELECT_ALL)) {
            JSONArray jsonArray = new JSONArray(connRs);
            if (jsonArray.length() == 0) {
                return "No data found";
            }
            String rs = "";
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String name = jsonObject.getString("name");
                rs += name;
            }
            return rs;
        } else if (action.equals(SELECT_ONE)) {
            JSONObject jsonObject = new JSONObject(connRs);
            String user = jsonObject.getString("user");
            if (user == null || user.equals("null")) {
                return "No date for this id";
            } else {
                return jsonObject.getString("name");
            }
        }
    } catch (Exception e) {
    }
    return null;
}

@Override
protected void onPostExecute(Object result) {
    super.onPostExecute(result);
    activity.viewResultMessage(result);
}

/**
 * connect to server with url and parameters
 *
 * @param url
 * @param params
 * @return
 */
public static String connect(String url, ArrayList<NameValuePair> params) {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    try {
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(params));
        HttpResponse httpResponse = httpClient.execute(httpPost);

        int status = httpResponse.getStatusLine().getStatusCode();
        if (status == 200) {
            HttpEntity httpEntity = httpResponse.getEntity();
            return EntityUtils.toString(httpEntity);
        }
    } catch (SocketTimeoutException ex) {
        Log.d("RS", "SocketTimeoutException: " + ex.toString());
    } catch (SocketException ex) {
        Log.d("RS", "SocketException: " + ex.toString());
    } catch (Exception e) {
        Log.d("RS", "Connect EX: " + e.toString());
        e.printStackTrace();
    }
    return null;
}
}

if anyone can help i will be so thankful

1 Answer 1

1

The log message:

    at com.example.nada.mysqldemo.MainActivity.viewResultMessage(MainActivity.java:89)

points to the following line in viewResultMessage:

showToast(result.toString());

This means that result is null. Where does result come from? It comes from this call in onPostExecute:

activity.viewResultMessage(result);

Where does the result come from here? According to the AsyncTask documentation:

The specified result is the value returned by doInBackground(Params...).

So, in your doInBackground method, you're returning null. The problem is probably here:

} catch (Exception e) {
}
return null;

In these lines, you are catching any possible exception that might happen, ignoring the exception, and returning null. This causes the behaviour you observed.

to fix this, find out what exception is being caught here, and fix that problem. You may also consider returning something other than null in this case.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.