Firas Chebbah
Firas Chebbah

Reputation: 11

Android, having a probleme with a null value

their is a problem in my code with android.The variable user return always the value NULL Actualy this class is for my homepage, it allows the connection to the user acount.

my probleme like i said is in the variable user. Actualy this variable have a null value and then it will change. by the way i am sorry if i have some trouble to communicate the probleme using english, it s not my mother language :)


  1. This is the code of the class where i have the probleme;

package com.medbac.exemple.activity;

import java.util.Calendar;
import java.util.Locale;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.medbac.exemple.download.ServiceHandler;
import com.medbac.exemple.model.User;

public class AcceuilFragment extends Fragment implements OnClickListener {

private ProgressDialog pDialog;

// URL 
//private static String url = "http://infraction-routier-json.esy.es/user_eber.php?";
 private static String url = "http://mf-json-app-inf.esy.es/user_hber.php?";
 private static String url_param = "";
  // c
private static final String TAG_TAB = "user";

//private static final String TAG_DTYPE = "DTYPE";
private static final String TAG_CIN = "CIN";
private static final String TAG_DTYPE = "DTYPE";
private static final String TAG_PWD = "PWD";
private static final String TAG_PRENOM = "PRENOM";
private static final String TAG_MAIL = "MAIL";
private static final String TAG_DATE = "DATE";
private static final String TAG_NOM = "NOM";
private static final String TAG_LOGIN = "LOGIN";
private static final String TAG_ADR="ADR";
//private static final String TAG_GRADE = "grade";

public static User user = null;
public static boolean payment;

Button btn_login, btn_sign_up;
EditText edit_login, edit_sign_up;
View rootView;
TextView txt_consult, txt_payment, dateAuj;

// tableau json
JSONArray userJSON = null;

public AcceuilFragment() {}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    rootView = inflater.inflate(R.layout.fragment_acceuil, container, false);

    Calendar newCalendar = Calendar.getInstance();
    String date = newCalendar.get(Calendar.DAY_OF_MONTH)+"-" +newCalendar.get(Calendar.MONTH)+"-"+ newCalendar.get(Calendar.YEAR);
    //sCalendar = Calendar.getInstance();
    String dayLongName = newCalendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.getDefault());

    dateAuj = (TextView) rootView.findViewById(R.id.dateJ);
    dateAuj.setText(dayLongName+" "+date);

    TextView txtAutho = (TextView) rootView.findViewById(R.id.txt_autho);
    String chAutho = getResources().getString(R.string.se_connecter);
    txtAutho.setText(Html.fromHtml(chAutho));

    txt_consult = (TextView) rootView.findViewById(R.id.txt_consultation);
    String chCons = getResources().getString(R.string.mes_inf);
    txt_consult.setText(Html.fromHtml(chCons));
    txt_consult.setOnClickListener(this);

    txt_payment = (TextView) rootView.findViewById(R.id.txt_payment);
    String chPay = getResources().getString(R.string.mes_amen);
    txt_payment.setText(Html.fromHtml(chPay));
    txt_payment.setOnClickListener(this);

    btn_login = (Button) rootView.findViewById(R.id.btn_log_in);
    btn_sign_up = (Button) rootView.findViewById(R.id.btn_sign_up);

    btn_login.setOnClickListener(this);
    btn_sign_up.setOnClickListener(this);

    edit_login = (EditText) rootView.findViewById(R.id.edit_login);
    edit_sign_up = (EditText) rootView.findViewById(R.id.edit_mp);
    return rootView;
}

private class GetUser extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        /*
         * Cette fonction contiendra le code exécuté au préalable, par exemple:
         *  -Affichage d'une ProgressBar 
         *      =rond qui tourne pour indiquer une attente
         *      =Barre de progression
         *  -...
         */
        pDialog = new ProgressDialog(getActivity());
        pDialog.setMessage("chargement... ");
        pDialog.setCancelable(false);
        pDialog.show();

    }

    @Override
    protected Void doInBackground(Void... arg0) {
        /*
         * Ici, le code qui doit être exécuté dans l'AsyncTask, par exemple:
         *  -Une requête de base de données
         *  -Un appel à un Web Service
         *  -...
         */

        // service handler : parse 
        ServiceHandler sh = new ServiceHandler();

        // get response
        String jsonStr = sh.makeServiceCall(url_param, ServiceHandler.GET);

        Log.d("Response: user", "> " + jsonStr);

        if (jsonStr != null) {
            try {

                JSONObject jsonObj = new JSONObject(jsonStr);

                // Get JSON Array 
                userJSON = jsonObj.getJSONArray(TAG_TAB);

                for (int i = 0; i < userJSON.length(); i++) {
                    JSONObject c = userJSON.getJSONObject(i);

                    String cin = c.getString(TAG_CIN);
                    String dtype = c.getString(TAG_DTYPE);
                    String pwd = c.getString(TAG_PWD);
                    String prenom = c.getString(TAG_PRENOM);
                    String mail = c.getString(TAG_MAIL);
                    String date = c.getString(TAG_DATE);
                    String nom = c.getString(TAG_NOM);
                    String login = c.getString(TAG_LOGIN);                                      
                    String adr = c.getString(TAG_ADR);

                    user = new User(cin, dtype, pwd, prenom, mail, date, nom, login,adr);
                    getActivity().invalidateOptionsMenu();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            Log.e("ServiceHandler", "Couldn't get any data from the url");
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
         /*
         * Ici, le code exécuté une fois le traitement terminé, par exemple:
         *  -Mise à jour de l'affichage
         *  -Affichage d'une pop-up indiquant la fin du traitement
         *  -Désactivation de la ProgressBar
         *  -...
         */
        // Désactivation de la ProgressBar
        if (pDialog.isShowing())
            pDialog.dismiss();
        /**
         * Updating parsed JSON data into ListView
         * */
        if(user == null){
            Toast.makeText(getActivity(), "ereur", Toast.LENGTH_SHORT).show();
        }else {
            Toast.makeText(getActivity(), "valide", Toast.LENGTH_SHORT).show();
            rootView.findViewById(R.id.identifiant).setVisibility(View.GONE);
        }

    }

}

@Override
public void onClick(View v) {
    if(v.getId() == btn_login.getId()){

        url_param = url +"LOGIN="+edit_login.getText().toString()+"&PWD="+edit_sign_up.getText().toString();
        edit_login.setText("");
        edit_sign_up.setText("");

        Log.e("url", url_param);
        new GetUser().execute();
    }else if (v.getId() == btn_sign_up.getId()){
        Intent i = new Intent(getActivity(), Inscription.class);
        startActivity(i);

    }else if (v.getId() == txt_consult.getId()){
        Fragment fragment = new MesInfractionFragment();
        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction()
                .replace(R.id.frame_container, fragment).commit();
        (TabBarMenu.mDrawerList).setItemChecked(1, true);
        (TabBarMenu.mDrawerList).setSelection(1);
        getActivity().getActionBar().setTitle("Mes Infractions");
        payment = false;        
        //Toast.makeText(getActivity(), "consult cliced", Toast.LENGTH_SHORT).show();

    }else if (v.getId() == txt_payment.getId()){
        if(user == null){
            Toast.makeText(getActivity(), "il faut inscrire d'abaure", Toast.LENGTH_SHORT).show();
        }else {
            Fragment fragment = new MesInfractionFragment();
            FragmentManager fragmentManager = getFragmentManager();
            fragmentManager.beginTransaction()
                    .replace(R.id.frame_container, fragment).commit();
            (TabBarMenu.mDrawerList).setItemChecked(1, true);
            (TabBarMenu.mDrawerList).setSelection(1);
            getActivity().getActionBar().setTitle("Mes Infractions");
            payment = true;
        }   
    }
}

}


And this is the model


package com.medbac.exemple.model;

public class User {


    //"cin":"22","login":"rr","password":"rr","nom":"rr","prenom":"rr",
    //"grade":"2","matricule_fiscal":"rr","num_carte_sejour":"2","num_tel":"888","dtype":"r"


    //public String d_type;
    public String cin;
    public String dtype;
    public String pwd;
    public String prenom;
    public String mail;
    public String date;
    public String nom;
    public String login;
    public String adr;
    //public String grade;

    public User (String cin, String dtype, String pwd, String prenom, String mail,String date, 
            String nom, String login, String adr){

        this.cin = cin;
        this.dtype = dtype;
        this.pwd = pwd;
        this.prenom = prenom;
        this.mail = mail;
        this.date = date;
        this.nom = nom;
        this.login = login;
        this.adr=adr;
    }

}

  1. And this is my verbose

05-29 01:01:17.616: I/Timeline(26616): Timeline: Activity_idle id: android.os.BinderProxy@219ada3c time:28441294
05-29 01:01:17.616: V/ActivityThread(26616): updateVisibility : ActivityRecord{5022dc9 token=android.os.BinderProxy@219ada3c {com.medbac.exemple.activity/com.medbac.exemple.activity.TabBarMenu}} show : true
05-29 01:01:18.651: I/Timeline(26616): Timeline: Activity_idle id: android.os.BinderProxy@219ada3c time:28442332
05-29 01:03:18.096: V/ActivityThread(26616): updateVisibility : ActivityRecord{5022dc9 token=android.os.BinderProxy@219ada3c {com.medbac.exemple.activity/com.medbac.exemple.activity.TabBarMenu}} show : true
05-29 01:03:18.231: W/IInputConnectionWrapper(26616): getTextBeforeCursor on inactive InputConnection
05-29 01:03:18.241: W/IInputConnectionWrapper(26616): getCursorCapsMode on inactive InputConnection
05-29 01:03:18.271: W/IInputConnectionWrapper(26616): getCursorCapsMode on inactive InputConnection
05-29 01:03:18.436: W/IInputConnectionWrapper(26616): getTextBeforeCursor on inactive InputConnection
05-29 01:03:18.436: W/IInputConnectionWrapper(26616): getSelectedText on inactive InputConnection
05-29 01:03:18.436: W/IInputConnectionWrapper(26616): getTextAfterCursor on inactive InputConnection
05-29 01:04:35.561: I/Timeline(26616): Timeline: Activity_idle id: android.os.BinderProxy@219ada3c time:28639242
05-29 01:04:36.651: D/ViewRootImpl(26616): ViewPostImeInputStage ACTION_DOWN
05-29 01:04:38.801: D/ViewRootImpl(26616): ViewPostImeInputStage ACTION_DOWN
05-29 01:04:43.561: D/ViewRootImpl(26616): ViewPostImeInputStage ACTION_DOWN
05-29 01:04:43.616: E/url(26616): http://mf-json-app-inf.esy.es/user_hber.php?LOGIN=ss&PWD=ss
05-29 01:04:43.686: E/(26616): [android_ws] Format: 5, Width: 1002, Height: 288
05-29 01:04:43.691: E/(26616): [android_ws] Format: 5, Width: 1002, Height: 288
05-29 01:04:43.691: E/(26616): [android_ws] Format: 5, Width: 1002, Height: 288
05-29 01:04:43.691: E/(26616): [android_ws] Format: 5, Width: 1002, Height: 288
05-29 01:04:43.716: E/(26616): [android_ws] Format: 5, Width: 1080, Height: 1920
05-29 01:04:43.716: E/(26616): [android_ws] Format: 5, Width: 1080, Height: 1920
05-29 01:04:43.721: E/(26616): [android_ws] Format: 5, Width: 1002, Height: 288
05-29 01:04:43.721: E/(26616): [android_ws] Format: 5, Width: 1002, Height: 288
05-29 01:04:43.736: E/(26616): [android_ws] Format: 5, Width: 1080, Height: 1920
05-29 01:04:43.736: E/(26616): [android_ws] Format: 5, Width: 1080, Height: 1920
05-29 01:04:43.741: E/(26616): [android_ws] Format: 5, Width: 1002, Height: 288
05-29 01:04:43.741: E/(26616): [android_ws] Format: 5, Width: 1002, Height: 288
05-29 01:04:43.876: I/System.out(26616): AsyncTask #2 calls detatch()
05-29 01:04:43.881: D/Response: user(26616): > {"utilisateur":[{"CIN":"1234567","DTYPE":"Financier","PWD":"ss","PRENOM":"saif","MAIL":"hhhh","DATE":null,"NOM":"mhamdi","LOGIN":"ss","ADR":null}]}
05-29 01:04:43.881: W/System.err(26616): org.json.JSONException: No value for user
05-29 01:04:43.886: W/System.err(26616):    at org.json.JSONObject.get(JSONObject.java:389)
05-29 01:04:43.886: W/System.err(26616):    at org.json.JSONObject.getJSONArray(JSONObject.java:584)
05-29 01:04:43.886: W/System.err(26616):    at com.medbac.exemple.activity.AcceuilFragment$GetUser.doInBackground(AcceuilFragment.java:147)
05-29 01:04:43.886: W/System.err(26616):    at com.medbac.exemple.activity.AcceuilFragment$GetUser.doInBackground(AcceuilFragment.java:1)
05-29 01:04:43.886: W/System.err(26616):    at android.os.AsyncTask$2.call(AsyncTask.java:288)
05-29 01:04:43.886: W/System.err(26616):    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
05-29 01:04:43.886: W/System.err(26616):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
05-29 01:04:43.886: W/System.err(26616):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
05-29 01:04:43.886: W/System.err(26616):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
05-29 01:04:43.886: W/System.err(26616):    at java.lang.Thread.run(Thread.java:818)
05-29 01:04:43.921: E/ViewRootImpl(26616): sendUserActionEvent() mView == null
05-29 01:04:43.936: E/(26616): [android_ws] Format: 5, Width: 1080, Height: 1920
05-29 01:04:43.936: E/(26616): [android_ws] Format: 5, Width: 1080, Height: 1920

  1. AND finaly this is the php code

<?php   
    $mm=mysqli_connect("...","...","....");
    mysqli_select_db($mm,"...");

    $l = $_GET['LOGIN'];
    $mp = $_GET['PWD'];

    $sql = mysqli_query($mm,"SELECT * FROM user WHERE LOGIN = '$l' AND PWD = '$mp'");

    $tab = array();
    //Retourne le nombre de lignes dans un résultat
    $nb_ligne=mysqli_num_rows($sql);

    if($nb_ligne >= 1){

    while($ligne = mysqli_fetch_array($sql,MYSQL_ASSOC)){
    //mysqli_fetch_array
    //Retourne une ligne de résultat sous la forme d'un tableau associatif, d'un tableau indexé, ou les deux
    //Le second argument optionnel est une constante indiquant quel type de tableau doit être renvoyé à partir de la ligne de données courante.
$tab ["utilisateur"] [] = $ligne;
    }     }

echo $v = str_replace('\\/','/',json_encode($tab));
//json_decode — Décode une chaîne JSON
//Récupère une chaîne encodée JSON et la convertit en une variable PHP.
mysqli_close($mm);

?>

Upvotes: 1

Views: 444

Answers (2)

NaseemH
NaseemH

Reputation: 408

You need to walk us a little bit through the execution of the code.

Please provide us with some debugging lines like checking if the clicks actually work, and if the code execution really gets to the doInBackground callback.

Best of luck.

Edit: You are getting a JSON exception at some point. And here is why I guess. You're trying to get the JSON array with the wrong key associated to it.

05-29 01:04:43.881: D/Response: user(26616): > {"utilisateur":[{"CIN":"1234567","DTYPE":"Financier","PWD":"ss","PRENOM":"saif","MAIL":"hhhh","DATE":null,"NOM":"mhamdi","LOGIN":"ss","ADR":null}]}

The first JSON object pair has the key "utilisateur", and a JSON array as its value. Yet in doInBackground callback you're trying to get exactly the same value with a different key "user" that does not exist ( "user" is assigned to TAG_TAB in this line):

private static final String TAG_TAB = "user";

Try changing this line to "utilisateur" and see if you still get the same JSON exception.

Upvotes: 1

LBes
LBes

Reputation: 3456

Do you even get to the part of your code when you're instantiating the user? That's the only reason I can think of. What is your output? Without a little bit of debugging on your part and given here it's difficult to try and see where the error comes from. All I can think of is that you never reach

user = new User(...)

Upvotes: 1

Related Questions