2016-02-14 3 views
0

Этот код используется для создания регистрационной формы с помощью json webservice, но когда я запускаю приложение, он возвращает сообщение об ошибке.Json webservice регистрация в android studio

import android.app.Activity; 
import android.app.ProgressDialog; 
import android.content.Intent; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.TextView; 
import android.widget.Toast; 
import org.apache.http.NameValuePair; 
import org.apache.http.message.BasicNameValuePair; 
import org.json.JSONException; 
import org.json.JSONObject; 
import java.util.*; 
import java.util.regex.Matcher; 
import java.util.regex.Pattern; 

public class Register extends Activity implements View.OnClickListener{ 
EditText editTextName,editTextemail,editTextmobile, editTextUserName,editTextPassword; 
TextView editTextsignin; 
Button btnCreateAccount; 
private ProgressDialog pDialog; 
// JSON parser class 
JSONParser jsonParser = new JSONParser(); 

private static final String LOGIN_URL = "http://beauty.limitscale.com/webservices/userregister"; 

private static final String TAG_SUCCESS = "success"; 
private static final String TAG_MESSAGE = "message"; 
LoginDataBaseAdapter loginDataBaseAdapter; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_register); 

    editTextName=(EditText)findViewById(R.id.name); 
    editTextemail=(EditText)findViewById(R.id.email); 
    editTextmobile=(EditText)findViewById(R.id.mobile); 
    editTextUserName=(EditText)findViewById(R.id.username); 
    editTextPassword=(EditText)findViewById(R.id.password); 
    editTextsignin=(TextView)findViewById(R.id.login); 
    btnCreateAccount = (Button) findViewById(R.id.register); 
    // Attached listener for login GUI button 


    editTextsignin.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 
      Intent intentSignUP = new Intent(Register.this, Login.class); 
      startActivity(intentSignUP); 
     } 
    }); 

    btnCreateAccount.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 

      String email = editTextemail.getText().toString(); 
      if (!isValidEmail(email)) { 
       editTextemail.setError("Invalid Email"); 
      } 

      String name = editTextName.getText().toString(); 
      if (!isValidName(name)) { 
       editTextName.setError("Invalid Name"); 
      } 

      String mobile = editTextmobile.getText().toString(); 
      if (!isValidMobile(mobile)) { 
       editTextmobile.setError("Invalid Mobile number"); 
      } 

      String userName=editTextUserName.getText().toString(); 
      if (!isValidUsername(userName)) { 
       editTextUserName.setError("Invalid UserName"); 
      } 
      String password=editTextPassword.getText().toString(); 
      if (!isValidPassword(password)) { 
       editTextPassword.setError("Invalid Password"); 
      } 
          if(userName.equals("")||password.equals("")||email.equals("")||name.equals("")||mobile.equals("")) 
      { 
       Toast.makeText(getApplicationContext(), "Field Vaccant", Toast.LENGTH_LONG).show(); 
       return; 
      } 

      else 
      {      
       Toast.makeText(getApplicationContext(), "Account Successfully Created ", Toast.LENGTH_LONG).show(); 

       Intent intent = new Intent(Register.this, MainActivity.class); 
       startActivity(intent); 
      } 
      new CreateUser().execute(); 
     } 
    }); 
} 

@Override 
public void onClick(View v) {   
    new CreateUser().execute(); 
} 
private boolean isValidName(String name) { 
    if (name != null && name.length() > 6) { 
     return true; 
    } 
    return false; 
} 
private boolean isValidUsername(String userName) { 
    if (userName != null && userName.length() > 6) { 
     return true; 
    } 
    return false; 
} 
private boolean isValidPassword(String password) { 
    if (password != null && password.length() > 6) { 
     return true; 
    } 
    return false; 
} 
private boolean isValidMobile(String mobile) { 
    if (mobile != null && mobile.length() == 10) { 
     return true; 
    } 
    return false; 
} 
private boolean isValidEmail(String email) { 
    String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" 
      + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; 
    Pattern pattern = Pattern.compile(EMAIL_PATTERN); 
    Matcher matcher = pattern.matcher(email); 
    return matcher.matches(); 
} 

class CreateUser extends AsyncTask<String, String, String> { 

    /** 
    * Before starting background thread Show Progress Dialog 
    * */ 
    boolean failure = false; 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     pDialog = new ProgressDialog(Register.this); 
     pDialog.setMessage("Creating User..."); 
     pDialog.setIndeterminate(false); 
     pDialog.setCancelable(true); 
     pDialog.show(); 
    } 

    @Override 
    protected String doInBackground(String... args) { 
     // TODO Auto-generated method stub 
     // Check for success tag 
     int success; 
     String name = editTextName.getText().toString(); 
     String email = editTextemail.getText().toString(); 
     String mobile = editTextmobile.getText().toString(); 
     String username = editTextUserName.getText().toString(); 
     String password = editTextPassword.getText().toString(); 
     try {     
      java.util.List<NameValuePair> params = new ArrayList<NameValuePair>(); 
      params.add(new BasicNameValuePair("customername", name)); 
      params.add(new BasicNameValuePair("useremail", email)); 
      params.add(new BasicNameValuePair("usernumber", mobile)); 
      params.add(new BasicNameValuePair("username", username)); 
      params.add(new BasicNameValuePair("password", password)); 

      Log.d("request!", "starting"); 

      JSONObject json = jsonParser.makeHttpRequest(
        LOGIN_URL, "POST", params); 

      // full json response 
      Log.d("Login attempt", json.toString()); 

      // json success element 
      success = json.getInt(TAG_SUCCESS); 
      if (success == 1) { 
       Log.d("User Created!", json.toString()); 
       finish(); 
       return json.getString(TAG_MESSAGE); 
      }else{ 
       Log.d("Login Failure!", json.getString(TAG_MESSAGE)); 
       return json.getString(TAG_MESSAGE); 

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

     return null; 

    } 
    /** 
    * After completing background task Dismiss the progress dialog 
    * **/ 
    protected void onPostExecute(String file_url) { 
     // dismiss the dialog once product deleted 
     pDialog.dismiss(); 
     if (file_url != null){ 
      Toast.makeText(Register.this, file_url, Toast.LENGTH_LONG).show(); 
     } 
    } 
}} 

Я новичок в WebService, пожалуйста, помогите мне, я не знаю, где я сделал макияж

JSONParser

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.HttpGet; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.client.utils.URLEncodedUtils; 
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() { 
} 

// function get json from url 
// by making HTTP POST or GET mehtod 
public JSONObject makeHttpRequest(String url, String method, 
            List<NameValuePair> params) { 

    // Making HTTP request 
    try { 

     // check for request method 
     if(method == "POST"){ 
      // request method is POST 
      // 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(); 

     }else if(method == "GET"){    
      DefaultHttpClient httpClient = new DefaultHttpClient(); 
      String paramString = URLEncodedUtils.format(params, "utf-8"); 
      url += "?" + paramString; 
      HttpGet httpGet = new HttpGet(url); 

      HttpResponse httpResponse = httpClient.execute(httpGet); 
      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(); 
    } 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; 
}} 

Вход

02-14 15:58:59.174 15671-15671/com.example.limitscale.beautylog D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002 
02-14 15:58:59.254 15671-15671/com.example.limitscale.beautylog D/dalvikvm﹕ GC_FOR_ALLOC freed 1076K, 10% free 69763K/76748K, paused 17ms, total 17ms 
02-14 15:58:59.274 15671-15671/com.example.limitscale.beautylog I/dalvikvm-heap﹕ Grow heap (frag case) to 83.034MB for 11494128-byte allocation 
02-14 15:58:59.564 15671-15737/com.example.limitscale.beautylog D/Login attempt﹕ {"data":null,"message":null,"status":"Failed"} 
02-14 15:58:59.584 15671-15737/com.example.limitscale.beautylog W/System.err﹕ org.json.JSONException: No value for success 
02-14 15:58:59.584 15671-15737/com.example.limitscale.beautylog W/System.err﹕ at org.json.JSONObject.get(JSONObject.java:355) 
02-14 15:58:59.584 15671-15737/com.example.limitscale.beautylog W/System.err﹕ at org.json.JSONObject.getInt(JSONObject.java:444) 
02-14 15:58:59.584 15671-15737/com.example.limitscale.beautylog W/System.err﹕ at com.example.limitscale.beautylog.Register$CreateUser.doInBackground(Register.java:193) 
02-14 15:58:59.584 15671-15737/com.example.limitscale.beautylog W/System.err﹕ at com.example.limitscale.beautylog.Register$CreateUser.doInBackground(Register.java:147) 
02-14 15:58:59.594 15671-15737/com.example.limitscale.beautylog W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:288) 
02-14 15:58:59.594 15671-15737/com.example.limitscale.beautylog W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:237) 
02-14 15:58:59.594 15671-15737/com.example.limitscale.beautylog W/System.err﹕ at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 
02-14 15:58:59.594 15671-15737/com.example.limitscale.beautylog W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 
02-14 15:58:59.594 15671-15737/com.example.limitscale.beautylog W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 
02-14 15:58:59.594 15671-15737/com.example.limitscale.beautylog W/System.err﹕ at java.lang.Thread.run(Thread.java:841) 
02-14 15:58:59.904 15671-15671/com.example.limitscale.beautylog I/Timeline﹕ Timeline: Activity_idle id: [email protected] time:5095895 

вот мой LogCat сообщение

+0

Пожалуйста, авторизуйтесь 'json.getInt (TAG_SUCCESS);' и скажите мне, каков был результат? Или напишите свой стек, который поможет вам определить вашу проблему. –

ответ

1

Вы пытаетесь получить доступ ключа, который не существует.

Форма ответа сервера заключается в следующем:

D/Login attempt﹕ {"data":null,"message":null,"status":"Failed"} 
W/System.err﹕ org.json.JSONException: No value for success 

Вы можете проверить, если он существует, прежде чем использовать его, как это:

if (json.has("status")) { 
    String status = json.getString("status")); 
} 


UPDATE:
Вы можете изменить следующий тег:

private static final String TAG_SUCCESS = "success"; 

Для этого:

private static final String TAG_SUCCESS = "status"; 

Возможно изменить имя переменной, скажем, TAG_STATUS

+0

Так как я могу его изменить, на самом деле я проверил его, используя почтальон, но не обновил –

+0

Я отредактировал свой ответ. Надеюсь, я правильно понял ваш вопрос. Если вы спросите, как вы должны получить доступ к конечной точке api (сообщение, получить, какие параметры), тогда вам нужно будет получить доступ к серверному коду или документации. @SivakumarS –

+0

Я получил его, но внес изменения, но моя функция не работает –

Смежные вопросы