繁体   English   中英

根据Json响应添加吐司

[英]Add Toasts depending on Json reponse

我有这样的代码,对我来说很好用,并允许我访问数据库。 唯一的问题是,如果主键值重复,我想添加消息,Toasts或某些东西来显示错误...

这是我的asyncTask的代码(我添加了Toast,但是没有用:()

Button con=(Button)findViewById(R.id.inscription);
con.setOnClickListener(new OnClickListener() {
    public void onClick(View v){
        new CreateNewUser().execute();
        }
    });
}

class CreateNewUser extends AsyncTask<String, String, String> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

protected String doInBackground(String... args) {
    @SuppressWarnings("deprecation")
    Date d=new Date(an-2800,mn,jn);
    Date d1=new Date(ap-2800,mp,jp);
    String datenaiss=d.toString();
    String deliv=d1.toString(); 
    EditText pseud=(EditText) findViewById(R.id.pseud);
    String pseudo = pseud.getText().toString();
    EditText name=(EditText) findViewById(R.id.nom);
    String nom = name.getText().toString();
    EditText prenom=(EditText) findViewById(R.id.pren);
    String pren =prenom.getText().toString();
    EditText cinn=(EditText) findViewById(R.id.cin);
    String cin = cinn.getText().toString();
    EditText ag=(EditText) findViewById(R.id.age);
    String age = ag.getText().toString();
    EditText tele=(EditText) findViewById(R.id.tel);
    String tel = tele.getText().toString();
    EditText mail=(EditText) findViewById(R.id.email);
    String email = mail.getText().toString();
    EditText adress=(EditText) findViewById(R.id.adresse);
    String adresse = adress.getText().toString();
    EditText motdp=(EditText) findViewById(R.id.pwd);
    String pwd = motdp.getText().toString();
    EditText vill=(EditText) findViewById(R.id.ville);
    String ville = vill.getText().toString();
    EditText numpermi=(EditText) findViewById(R.id.numperm);
    String numperm = numpermi.getText().toString();         
    String x="http://192.168.1.5/add_user.php";
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("pseudo", pseudo));
    params.add(new BasicNameValuePair("mdp", pwd));
    params.add(new BasicNameValuePair("datenaiss", datenaiss));
    params.add(new BasicNameValuePair("deliv", deliv));
    params.add(new BasicNameValuePair("nom", nom));
    params.add(new BasicNameValuePair("prenom", pren));
    params.add(new BasicNameValuePair("cin", cin));
    params.add(new BasicNameValuePair("age", age));
    params.add(new BasicNameValuePair("tel", tel));
    params.add(new BasicNameValuePair("email", email));
    params.add(new BasicNameValuePair("adresse", adresse));
    params.add(new BasicNameValuePair("ville", ville));
    params.add(new BasicNameValuePair("numperm", numperm));
    JSONObject json;

    try {
        json = jsonParser.makeHttpRequest(x,"POST", params);
        Log.d("Create Response", json.toString());
        try {
            int success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
                Toast.makeText(MainActivity.this,"Ajouté avec succés", Toast.LENGTH_LONG).show();}
            else
                Toast.makeText(getBaseContext(),"echec",Toast.LENGTH_LONG).show();}
        catch(JSONException e) {
            e.printStackTrace();
        }

    } catch (JSONException e1) {
    // TODO Auto-generated catch block
        e1.printStackTrace();
    }

// check log cat fro response
return null;}
protected void onPostExecute(String file_url) {
     // dismiss the dialog once done
}

这是我的php add_user文件的代码:...........

// mysql inserting a new row
$result = mysql_query("INSERT INTO utilisateur VALUES('$pseudo', '$mdp', '$nom', '$prenom','$cin', '$datenaiss', '$tel', '$email', '$adresse', '$ville', '$numperm', '$deliv')");

// check if row inserted or not
if ($result) {
    // successfully inserted into database
    $response["success"] = 1;
    $response["message"] = "Product successfully created.";

    // echoing JSON response
    echo json_encode($response);
} else {
    // failed to insert row
    $response["success"] = 0;
    $response["message"] = "Oops! An error occurred.";

    // echoing JSON response
    echo json_encode($response);
}
}?>

你们能告诉我该怎么办吗? 如果有不同的方式做同样的事情,我想尝试一下:D

您无法从后台线程触摸ui。 要显示Toast,您必须使用在ui线程上运行方法。 或使用异步任务的进度更新方法。 对于空值,请进行检查。 如果那样的话,它也会异常运行,并且有可能使应用程序崩溃。

您正在尝试在doInBackground方法内部创建Toast,但显然不能这样做,因为doInBackground是从后台线程调用的。 吐司只能在UI线程中创建。 因此,我建议您处理服务器响应,并在UI线程内执行的onPostExecute方法内创建Toasts。 您可以执行以下操作:

class MyCystomObject {

  private JSONObject json;
  private String file_url;

 public MyCystomObject(JSONObject json, String file_url) {
   this.json = json;
   this.file_url = file_url;
 }

 public void setJson(JSONObject json) { this.json = json; }

 public void setFile_url(String file_url) { this.file_url = file_url; }

 public JSONObject getJson() { return json; }

 public String getFile_url() { return file_url; }
}  

创建此类以保存您从服务器接收的JSON对象和“ file_url”字符串(我不知道如何将其准确传递给onPostExecute)并将其传递给onPostExecute。 因此,doInBackground和onPostExecute可能类似于:

  protected String doInBackground(String... args) {

    ....
    JSONObject json;
    MyCystomObject myCystomObject;

    json = jsonParser.makeHttpRequest(x,"POST", params);
    Log.d("Create Response", json.toString());

    myCystomObject = new MyCustomObject(json, your_file_url);

    return myCystomObject; 
  }



  protected void onPostExecute(MyCystomObject myCystomObject) {
      // here you can handle the responce you receive from server and display the appropriate toast message...
       JSONObject json = myCustomObject.getJson();
      try {
        int success = json.getInt(TAG_SUCCESS);
        if (success == 1) {
            Toast.makeText(MainActivity.this,"Ajouté avec succés", Toast.LENGTH_LONG).show();}
        else
            Toast.makeText(getBaseContext(),"echec",Toast.LENGTH_LONG).show();}
    catch(JSONException e) {
        e.printStackTrace();
    }
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM