1

я делаю систему лайков/дизлайков на анкету, и собствено код с ошибкой которую я не могу исправить. Извините код очень ужасный , недостаток опыта

код

  public class UserActivity extends Activity {

private static final String TAG = UserActivity.class.getSimpleName();
private static final String urlUser = "http://qwerty.hol.es/api/user.php?code=";
private static final String urlLike = "http://qwerty.hol.es/api/like.php?";
private ProgressDialog pDialog1;
private ProgressDialog pDialog2;
private Button btnLike;
private Button btnDisLike;
private static String like_type;
private static String like_to;
private SQLiteHandler db;


ImageLoader imageLoader = AppController.getInstance().getImageLoader();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_user);
    HashMap<String, String> user = db.getUserDetails();
    btnLike = (Button) findViewById(R.id.like);
    btnDisLike = (Button) findViewById(R.id.dislike);





    final String GetToLike = "unique_id="+user.get("uid")+"like_to="+like_to+"type="+like_type;

    // like
    btnLike.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {

            like_type = "1";

            pDialog1 = ProgressDialog.show(UserActivity.this, getString(R.string.processing), getString(R.string.wait));

            StringRequest likeReq = new StringRequest(Request.Method.GET,
                    urlLike +  GetToLike, new Response.Listener<String>() {

                @Override
                public void onResponse(String response) {
                    Log.d(TAG, "Like Response: " + response.toString());

                    hidePDialog1();


                    try {

                        JSONObject obj = new JSONObject(response);


                        String unique_id = obj.getString("name");

                        String like_to = obj.getString("like_to");

                        String type = obj.getString("like_type");



                        TextView txtLike_status = (TextView) findViewById(R.id.like_status);

                        txtLike_status.setText(like_to);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    VolleyLog.d(TAG, "Error: " + error.getMessage());
                    hidePDialog1();

                }
            });

            // Adding request to request queue
            AppController.getInstance().addToRequestQueue(likeReq);



        }
    });


    // dislike
    btnDisLike.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {


            like_type = "0";

            pDialog1 = ProgressDialog.show(UserActivity.this, getString(R.string.processing), getString(R.string.wait));

            StringRequest likeReq = new StringRequest(Request.Method.GET,
                    urlLike +  GetToLike, new Response.Listener<String>() {

                @Override
                public void onResponse(String response) {
                    Log.d(TAG, "Like Response: " + response.toString());

                    hidePDialog1();


                    try {

                        JSONObject obj = new JSONObject(response);


                        String unique_id = obj.getString("name");

                        String like_to = obj.getString("like_to");

                        String type = obj.getString("like_type");



                        TextView txtLike_status = (TextView) findViewById(R.id.like_status);

                        txtLike_status.setText(like_to);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    VolleyLog.d(TAG, "Error: " + error.getMessage());
                    hidePDialog1();

                }
            });

            // Adding request to request queue
            AppController.getInstance().addToRequestQueue(likeReq);





        }
    });











    String Code = getIntent().getStringExtra("code");


    pDialog2 = ProgressDialog.show(this, getString(R.string.id_people), getString(R.string.wait));

    StringRequest userReq = new StringRequest(Request.Method.GET,
            urlUser + Code, new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {
            Log.d(TAG, "User Response: " + response.toString());

            hidePDialog2();


            try {

                JSONObject obj = new JSONObject(response);


                String name = obj.getString("name");

                like_to = obj.getString("like_to");

                String second_name = obj.getString("second_name");

                String ThumbnailUrl = obj.getString("photo");


                imageLoader = AppController.getInstance().getImageLoader();

                NetworkImageView thumbNail = (NetworkImageView) findViewById(R.id.thumbnail);


                TextView txtUser = (TextView) findViewById(R.id.user);

                thumbNail.setImageUrl(ThumbnailUrl, imageLoader);

                txtUser.setText(name + " " + second_name);


            } catch (JSONException e) {
                e.printStackTrace();
            }


        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d(TAG, "Error: " + error.getMessage());
            hidePDialog2();

        }
    });

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(userReq);
}




@Override
public void onDestroy() {
    super.onDestroy();
    hidePDialog1();
    hidePDialog2();
}

private void hidePDialog1() {
    if (pDialog1 != null) {
        pDialog1.dismiss();
        pDialog1 = null;
    }
}

private void hidePDialog2() {
    if (pDialog2 != null) {
        pDialog2.dismiss();
        pDialog2 = null;
    }
}

  }

stacktrace:

FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.totalsx.liketomeet/com.qwerty.qwerty.UserActivity}: java.lang.NullPointerException
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2255)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2309)
    at android.app.ActivityThread.access$700(ActivityThread.java:157)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1289)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:176)
    at android.app.ActivityThread.main(ActivityThread.java:5317)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
    at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.NullPointerException
    at com.totalsx.liketomeet.UserActivity.onCreate(UserActivity.java:48)
    at android.app.Activity.performCreate(Activity.java:5326)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1097)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2218)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2309) 
    at android.app.ActivityThread.access$700(ActivityThread.java:157) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1289) 
    at android.os.Handler.dispatchMessage(Handler.java:99) 
    at android.os.Looper.loop(Looper.java:176) 
    at android.app.ActivityThread.main(ActivityThread.java:5317) 
    at java.lang.reflect.Method.invokeNative(Native Method) 
    at java.lang.reflect.Method.invoke(Method.java:511) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869) 
    at dalvik.system.NativeStart.main(Native Method) 

1 ответ 1

3

Согласно stackTrace у вас NullPoinerException в onCreate() методе Activity на 48 строке.

Судя по всему проблема в строчке

HashMap user = db.getUserDetails();

переменная db у вас неинициализирована и имеет значение null. Инициализировать её можно вызвав метод getWritableDatabase() экземпляра вашего класса SQLiteHandler.

//инициализируем переменную
SQLiteHandler dB = new SQLiteHandler(this);
//получаем доступ к базе данных
dB.getWritableDatabase();

Ваш ответ

Нажимая «Отправить ответ», вы соглашаетесь с условиями пользования и подтверждаете, что прочитали политику конфиденциальности.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.