2017-02-21 73 views
0

Я пытаюсь создать простой логин и, если он успешный, я пытаюсь сохранить ответ userid (uid) в общие настройки. Ниже приводится часть моего loginActivity.java и сообщения об ошибках:Android Volley Response

Ошибка 1

error: incompatible types: int cannot be converted to String 
    JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST, Config.LOGIN_URL, null, new Response.Listener<JSONObject>() { 

Ошибка 2

error: cannot find symbol 
    JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,Config.LOGIN_URL, null, new Response.Listener<JSONObject>() { 
           ^

символ: конструктор (интермедиат, String ,, >)

LoginActivity.java

import android.content.Context; 
import android.content.Intent; 
import android.content.SharedPreferences; 
import android.support.v7.app.ActionBar; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.support.v7.widget.AppCompatButton; 
import android.view.View; 
import android.widget.EditText; 
import android.widget.Toast; 

import org.json.JSONObject; 

import com.android.volley.Request.Method; 
import com.android.volley.AuthFailureError; 
import com.android.volley.RequestQueue; 
import com.android.volley.Response; 
import com.android.volley.toolbox.JsonObjectRequest; 
import com.android.volley.toolbox.Volley; 

import java.util.HashMap; 
import java.util.Map; 

public class LoginActivity extends AppCompatActivity implements View.OnClickListener { 

    //Defining views 
    private EditText editTextTCNO; 
    private EditText editTextMobile; 
    private AppCompatButton buttonLogin; 

    //boolean variable to check user is logged in or not 
    //initially it is false 
    private boolean loggedIn = false; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_login); 

     ActionBar actionBar = getSupportActionBar(); 
     actionBar.hide(); 

     //Initializing views 
     editTextTCNO = (EditText) findViewById(R.id.editTextTCNO); 
     editTextMobile = (EditText) findViewById(R.id.editTextMobile); 

     buttonLogin = (AppCompatButton) findViewById(R.id.loginButton); 

     //Adding click listener 
     buttonLogin.setOnClickListener(this); 
    } 

    @Override 
    protected void onResume() { 
     super.onResume(); 
     //In onresume fetching value from sharedpreference 
     SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE); 

     //Fetching the boolean value form sharedpreferences 
     loggedIn = sharedPreferences.getBoolean(Config.LOGGEDIN_SHARED_PREF, false); 

     //If we will get true 
     if(loggedIn){ 
      //We will start the Profile Activity 
      Intent intent = new Intent(LoginActivity.this, MainActivity.class); 
      startActivity(intent); 
     } 
    } 

    private void login() { 
     //Getting values from edit texts 
     final String tcno = editTextTCNO.getText().toString().trim(); 
     final String mobile = editTextMobile.getText().toString().trim(); 
     final String operation = "login"; 

     //Creating a string request 
     JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST, Config.LOGIN_URL, null, new Response.Listener<JSONObject>() { 
      @Override 
      public void onResponse(JSONObject response) { 
       String smsg = response.getString("msg"); 
       String pid = response.getString("uid"); 

       //If we are getting success from server 
       if(smsg == Config.LOGIN_SUCCESS){ 
        //Creating a shared preference 
        SharedPreferences sharedPreferences = LoginActivity.this.getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE); 

        //Creating editor to store values to shared preferences 
        SharedPreferences.Editor editor = sharedPreferences.edit(); 

        //Adding values to editor 
        editor.putBoolean(Config.LOGGEDIN_SHARED_PREF, true); 
        editor.putString(Config.UID_SHARED_PREF, pid); 

        //Saving values to editor 
        editor.commit(); 

        //Starting profile activity 
        Intent intent = new Intent(LoginActivity.this, MainActivity.class); 
        startActivity(intent); 
       }else{ 
        //If the server response is not success 
        //Displaying an error message on toast 
        Toast.makeText(LoginActivity.this, "Invalid username or password", Toast.LENGTH_LONG).show(); 
       } 
      } 
     }){ 
      @Override 
      protected Map<String, String> getParams() throws AuthFailureError { 
       Map<String,String> params = new HashMap<>(); 
       //Adding parameters to request 
       params.put(Config.KEY_TCNO, tcno); 
       params.put(Config.KEY_MOBILE, mobile); 
       params.put(Config.KEY_OPERATION, operation); 

       //returning parameter 
       return params; 
      } 
     }; 

     //Adding the string request to the queue 
     RequestQueue requestQueue = Volley.newRequestQueue(this); 
     requestQueue.add(jsonObjReq); 

    } 

    @Override 
    public void onClick(View v) { 
     //Calling the login function 
     login(); 
    } 
} 
+0

Я думаю, что вы импортировали неправильный 'Method.POST' –

+0

я редактировал LoginActivity.java, чтобы показать импорт, который один ошибается? @ cricket_007 – adams

+0

Возможно, нет ... Трудно сказать, на что указывает ошибка. Является ли 'Config.LOGIN_URL' целым числом? –

ответ

1

это мой полностью функциональный способ сделать запрос залпа, надеюсь, что это помогает

private JSONObject LoginJson() 
{ 
    JSONObject jsonBody = new JSONObject(); 
    try { 
     jsonBody.put("Username", "testUser"); 
     jsonBody.put("Password", "123456"); 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 
    return jsonBody; 
} 
public boolean identificarce() 
{ 
    RequestFuture<JSONObject> future = RequestFuture.newFuture(); 
    JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, URL.ServicioLogging, this.LoginJson(), future, future); 

    QueuHolder.getInstance(Login.contexto).getRequestQueue().add(request); 
    try { 
     JSONObject response = future.get(); 
     try 
     { 
      String NombreCompleto = response.getString("NombreCompleto"); 
      int id = response.getInt("id"); 
      //save results in shared preferences 
     } 
     catch (JSONException e) 
     { 
      e.printStackTrace(); 
     } 
    } 
    catch (Exception e) 
    { 
     e.printStackTrace(); 
     return false; 
    } 
    return true; 
} 
+0

Скомпилирует ли это? 'Запрос JsonObjectRequest; = new JsonObjectRequest' ... случайная точка с запятой? –

+0

нет, это не так. @ cricket_007 – adams

+0

jajajaja я забыл, раньше было: JsonObjectRequest request; request = new JsonObjectRequest (Request.Method.POST, URL.ServicioLogging, this.LoginJson(), будущее, будущее); Я тестировал, и он работает, я исправил в своем редактировании: P извините за это – karique