I created application to pass data from android device to web API.
1.As a first step user should login and if he is valid user application save the token value. 2.Then go to add product interface. In that interface user can add new products to the server. 3.To do this task user should pass token value to the header field at the API. 4.Other details into body field at the API.
This is my login activity
public class LoginActivity extends Activity {
private static final String TAG = RegisterActivity.class.getSimpleName();
private Button btnLogin;
private Button btnLinkToRegister;
private EditText inputEmail;
private EditText inputPassword;
private ProgressDialog pDialog;
private SessionManager session;
private SQLiteHandler db;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// SQLite database handler
db = new SQLiteHandler(getApplicationContext());
// Session manager
session = new SessionManager(getApplicationContext());
// Check if user is already logged in or not
if (session.isLoggedIn()) {
// User is already logged in. Take him to main activity
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String email = inputEmail.getText().toString().trim();
String password = inputPassword.getText().toString().trim();
// Check for empty data in the form
if (!email.isEmpty() && !password.isEmpty()) {
// login user
checkLogin(email, password);
} else {
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(),
"Please enter the credentials!", Toast.LENGTH_LONG)
.show();
}
}
});
// Link to Register Screen
btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
RegisterInfo.class);
startActivity(i);
finish();
}
});
}
/**
* function to verify login details in mysql db
*/
private void checkLogin(final String email, final String password) {
// Tag used to cancel the request
String tag_string_req = "req_login";
pDialog.setMessage("Logging in ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_LOGIN, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
//String token = jObj.getString("token");
// Check for error node in json
if (!error) {
// user successfully logged in
// Create login session
session.setLogin(true);
// Now store the user in SQLite
String uid = jObj.getString("uid");
JSONObject user = jObj.getJSONObject("user");
String name = user.getString("name");
String email = user.getString("email");
String created_at = user
.getString("created_at");
// Inserting row in users table
db.addUser(name, email, uid, created_at);
} else {
//Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
//e.printStackTrace();
// Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
// Launch main activity
String token=e.getMessage();
new Sharedpreference(token);
Intent intent = new Intent(LoginActivity.this,
Product_Dashboard.class);
startActivity(intent);
finish();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
@Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("email", email);
params.put("password", password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
This is my product activity
public class MainActivity extends Activity {
private EditText productName;
private EditText Category;
private EditText Description;
private EditText UnitPrice;
private EditText from;
private EditText to;
private EditText Quty;
RadioGroup priceoption;
RadioGroup Quantityoption;
Button Addproductbtn;
public static final String PREFS_NAME = "AOP_PREFS";
public final String PREFS_KEY = "AOP_PREFS_String";
private String Aceept = "@'application/vnd.fxhello.v1+json'";
private String token1;
private String Authontication = "Bearer$" +token1;
//--READ data
// String token = preferences.getString("var1", 0);
String price1 = "TRUE";
String qtySelect1 = "TRUE";
private String service1 = "";
private String limitedQty1 = "";
private String lqty1 = "";
public String getValue(Context context) {
SharedPreferences settings;
String text;
settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); //1
text = settings.getString(PREFS_KEY, null); //2
token1=text;
return text;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
productName = (EditText) findViewById(R.id.productnameeditText);
Category = (EditText) findViewById(R.id.CategoryeditText);
Description = (EditText) findViewById(R.id.DescriptioneditText);
UnitPrice = (EditText) findViewById(R.id.UnitPriceeditText);
from = (EditText) findViewById(R.id.FromeditText);
to = (EditText) findViewById(R.id.ToeditText);
Quty = (EditText) findViewById(R.id.EnterquantityeditText);
priceoption = (RadioGroup) findViewById(R.id.priceoption);
Quantityoption = (RadioGroup) findViewById(R.id.Quantityoption);
Addproductbtn =(Button)findViewById(R.id.AddNewProductbtn);
Addproductbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String price = price1.toString();
String unit_price = UnitPrice.getText().toString();
String up = unit_price.toString();
String price_range_from = from.getText().toString();
String prf = price_range_from.toString();
String price_range_to = to.getText().toString();
String prt = price_range_to.toString();
String product_name = productName.getText().toString();
String pn = product_name.toString();
String category = Category.getText().toString();
String ct = category.toString();
String description = Description.getText().toString();
String des = description.toString();
String qtySelect = qtySelect1.toString();
String qty = Quty.toString();
String service = service1.toString();
String limitedQty = limitedQty1.toString();
String lmtq = limitedQty.toString();
String lqty = lqty1.toString();
insertToDatabase(price, up, prf, prt, pn, ct, des, qty, service, lmtq, lqty);
Toast.makeText(getApplicationContext(), "New Product Added!", Toast.LENGTH_SHORT).show();
finish();
}
});
}
private void insertToDatabase(String price, String up, String prf, String prt, String pn, String ct, String des, String qty, String service, String lmtq, String lqty) {
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
String paraprice = params[0];
String paraunit_price = params[1];
String paraprice_range_from = params[2];
String paraprice_range_to = params[3];
String paraproduct_name = params[4];
String paracategory = params[5];
String paraDescription = params[6];
String paraqtySelect = params[7];
String paraqty = params[8];
String paraservice = params[10];
String paralimitedQty = params[11];
String paralqty = params[12];
String price = price1.toString();
String Up = up.toString();
String Prf = prf.toString();
String Prt = prt.toString();
String Pn = pn.toString();
String Ct = ct.toString();
String Des = des.toString();
String qtySelect = qtySelect1.toString();
String Lmtq = lmtq.toString();
String service = service1.toString();
String limitedQty = limitedQty1.toString();
String lqty = lqty1.toString();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("price", price));
nameValuePairs.add(new BasicNameValuePair("unit_price", Up));
nameValuePairs.add(new BasicNameValuePair("price_range_from", Prf));
nameValuePairs.add(new BasicNameValuePair("price_range_to", Prt));
nameValuePairs.add(new BasicNameValuePair("product_name", Pn));
nameValuePairs.add(new BasicNameValuePair("category", Ct));
nameValuePairs.add(new BasicNameValuePair("description", Des));
nameValuePairs.add(new BasicNameValuePair("qtySelect", qtySelect));
nameValuePairs.add(new BasicNameValuePair("lmtq", lmtq));
nameValuePairs.add(new BasicNameValuePair("service", service));
nameValuePairs.add(new BasicNameValuePair("limitedQty", limitedQty));
nameValuePairs.add(new BasicNameValuePair("lqty", lqty));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(
"http://uat.fxhello.com/api/seller/productCreate");
httpPost.setHeader("Accept", Aceept);
httpPost.setHeader("Authorization",Authontication);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return "success";
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(price, up, prf, prt, pn, ct, des, qty, service, lmtq, lqty);
}
}
I got this error
FATAL EXCEPTION: AsyncTask #3 Process: com.example.official2.xoxo, PID: 2364 java.lang.RuntimeException: An error occurred while executing doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:309) at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354) at java.util.concurrent.FutureTask.setException(FutureTask.java:223) at java.util.concurrent.FutureTask.run(FutureTask.java:242) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) at java.lang.Thread.run(Thread.java:818) Caused by: java.lang.ArrayIndexOutOfBoundsException: length=11; index=11 at com.example.official2.xoxo.MainActivity$1SendPostReqAsyncTask.doInBackground(MainActivity.java:143) at com.example.official2.xoxo.MainActivity$1SendPostReqAsyncTask.doInBackground(MainActivity.java:131) at android.os.AsyncTask$2.call(AsyncTask.java:295) at java.util.concurrent.FutureTask.run(FutureTask.java:237) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) at java.lang.Thread.run(Thread.java:818) 12-15 10:09:11.859 2364-2379/com.example.official2.xoxo E/EGL_emulation: tid 2379: eglSurfaceAttrib(1165): error 0x3009 (EGL_BAD_MATCH)