I'm trying to get the value the user enters in the userNameVar and passwordVar variables, and then compare them to the values stored in my database. However, when I enter the details, which are the same as what I have stored in my database, I get the following message:
Error message
Here is my login class code
public class Login extends AppCompatActivity implements View.OnClickListener {
private EditText usernameField;
private EditText passwordField;
private static Button login_btn;
TextView register_link;
String userNameVar = "";
String passwordVar = "";
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
User userObj;
DatabaseUserList databaseUserList = new DatabaseUserList();
private static final String TAG_SUCCESSFUL = "Successful";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_page);
login_btn = (Button) findViewById(R.id.login_button);
usernameField = (EditText) findViewById(R.id.etUsername);
passwordField = (EditText) findViewById(R.id.etPassword);
//starts to listen for clicks on this button
login_btn.setOnClickListener(this);
register_link = (TextView) findViewById(R.id.register_link);
register_link.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.login_button:
//null object reference problem here
Log.d("Username and password",
userNameVar = usernameField.getText().toString();
passwordVar = passwordField.getText().toString();
usernameField.getText().toString());
validateUser(userNameVar, passwordVar);
break;
}
}
private void validateUser (String username, String password)
{
new LogtheuserIn().execute();
}
private void resultsofloginAttmempt(User u)
{
if(u != null)
{
Log.d("User", userObj.toString() + "User must have logged in successfully");
}
}
private void userLoggedIn()
{
Intent intent = new Intent(this, FirstPage.class);
//User has to implement serializable
intent.putExtra("Userisin", userObj);
startActivity(intent);
}
public class LogtheuserIn extends AsyncTask<String,String,String>
{
#Override
protected void onPreExecute()
{
Log.d("onPrexecute", "on the preExecutePart");
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Loading users");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... args)
{
List<NameValuePair> arguements = new ArrayList<NameValuePair>();
try{
Log.d("This is the username ", "and password taken from the input fields");
String loginDetails = ServerConnection.SERVER_ADDRESS + "login.php?userName=" + userNameVar + "?password" + passwordVar;
JSONObject jObject = jParser.makeHttpRequest(loginDetails, "GET", arguements);
Log.d("All users", jObject.toString());
int success = jObject.getInt(TAG_SUCCESSFUL);
} catch (Exception e) {
pDialog.dismiss();
runOnUiThread(new Runnable()
{
public void run()
{
Toast.makeText(getApplicationContext(), "Problem with the server",
Toast.LENGTH_SHORT).show();
}
});
}
return null;
}
protected void onPostExecute(String dismissable)
{
//Dismiss the dialogue after we have
//gotten the user(s)
pDialog.dismiss();
Login.this.runOnUiThread(
new Runnable() {
public void run()
{
resultsofloginAttmempt(userObj);
Log.d("Array details", databaseUserList.getListOfUsers().toString());
}
}
);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_login, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Recheck findViewById(R.id.whatisyourrealid); because it's returning null.
Related
I am developing a new app that gets data from a local database and uploads it to the Cloud but, after some time, it shows a prompt that the app is not responding.
I have reviewed the logcat debugger log but can not identify the issue. I am using gennymotion as virtual device to test the app.
Can anyone help me resolve this?
public class MainActivity extends AppCompatActivity implements SmartScheduler.JobScheduledCallback,NavigationView.OnNavigationItemSelectedListener{
String str;
ProgressBar pb;
TextView textView;
private static final int JOB_ID = 1;
private static final String TAG = MainActivity.class.getSimpleName();
private static final String JOB_PERIODIC_TASK_TAG = "io.hypertrack.android_scheduler_demo.JobPeriodicTask";
String Ip="";
String Interval="";
private String intervalInMillisEditText;
JSONArray jsonArray;
static final String UrlPost = "serverIp";
final String TenantId = "Specific string";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Progress bar code is here
pb = (ProgressBar) findViewById(R.id.progressBar);
pb.setVisibility(View.GONE);
//for the textView of loading...
textView = (TextView) findViewById(R.id.textView);
//nevigations
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//get the interval values from Database
LoadDatabaseData();
}
public void LoadDatabaseData(){
List<IpAddressInverval> listIp = IpAddressInverval.listAll(IpAddressInverval.class);
for (IpAddressInverval ips:listIp) {
Ip= ips.getIpAddress();
Interval = ips.getInterval();
System.out.println("Ip "+Ip);
System.out.println("Interval is "+Interval);
}
}
public void gotoServicePage(View view){
//get the interval values from Database
LoadDatabaseData();
// Button btnstart = (Button) findViewById(R.id.button);
// btnstart.setVisibility(View.GONE);
if(Ip.matches("") || Interval.matches("")) {
Toast.makeText(this, "Please Fill the Parametters", Toast.LENGTH_SHORT).show();
}
// if(Interval.matches("")){
//
// Toast.makeText(this, "Please Fill the Parametters", Toast.LENGTH_SHORT).show();
//
// }
else
{
// CallApi();
SmartScheduler jobScheduler = SmartScheduler.getInstance(this);
// Check if any periodic job is currently scheduled
if (jobScheduler.contains(JOB_ID)) {
removePeriodicJob();
return;
}
// Create a new job with specified params
Job job = createJob();
if (job == null) {
Toast.makeText(MainActivity.this, "Invalid paramteres specified. " +
"Please try again with correct job params.", Toast.LENGTH_SHORT).show();
return;
}
// Schedule current created job
if (jobScheduler.addJob(job)) {
Toast.makeText(MainActivity.this, "Job successfully added!", Toast.LENGTH_SHORT).show();
}
}
}
//call the api and get the data
public void CallApi(){
String AddressIp = "http://"+Ip+":5700/api/values";
new AsyncHttpClient().get(AddressIp, new TextHttpResponseHandler() {
#Override
public void onStart() {
// pb.setVisibility(View.VISIBLE);
textView.setVisibility(View.VISIBLE);
textView.setText("Loading....");
}
#Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
Toast.makeText(MainActivity.this, responseString, Toast.LENGTH_SHORT).show();
}
#Override
public void onSuccess(int statusCode, Header[] headers, String responseString) {
str= responseString;
// Toast.makeText(MainActivity.this, "Data Received", Toast.LENGTH_SHORT).show();
try {
SpliterStringMethod(str);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
pb.setVisibility(View.GONE);
textView.setVisibility(View.GONE);
}
});
}
//spli the strinh into the array
public void SpliterStringMethod(String values) throws IOException, JSONException {
//unquote the string for the data..
values = values.replaceAll("^\"|\"$", "");
//split on the baseis of '#'
String[] lineString = values.split("#");
for (int i = 0; i < lineString.length; i++) {
double idTicket = 0;
System.out.println(lineString[i]);
String[] valuesString = lineString[i].split(",");
System.out.println("inner loop");
//fETCH THE ID FROM DB if ticket exist then update else insert into it
Ticket ticket = new Ticket();
List<Ticket> num = ticket.find(Ticket.class, "TICKETNO = " + valuesString[3]);
if (num.size() != 0) {
for (Ticket item : num) {
System.out.println("Fetching the id= " + item.getId());
idTicket = item.getId();
}
}
if (idTicket == 0) {
Ticket newTicket = new Ticket(Integer.parseInt(valuesString[1]), Integer.parseInt(valuesString[2])
, Integer.parseInt(valuesString[3]), Integer.parseInt(valuesString[4]),
Integer.parseInt(valuesString[5]));
newTicket.save();
System.out.println("Ticket Saved!..");
} else {
//update queue id
Ticket newqueuid = Ticket.findById(Ticket.class, (int) idTicket);
newqueuid.setPosition_in_queue(Integer.parseInt(valuesString[5])); // modify the values
newqueuid.save(); // updates the previous entry with new values.
System.out.println("Ticket Updated!..");
idTicket = 0;
}
}
}
//fetch the data from the Database
public void getTableData(){
//call the ticket table to get the values
List<Ticket> ticketAll = Ticket.listAll(Ticket.class);
jsonArray = new JSONArray();
for(int i=0;i<ticketAll.size();i++)
{
// JSONObject jGroup1 = new JSONObject();
Map jGroup1 = new LinkedHashMap();
jGroup1.put("track_no",ticketAll.get(i).getTrack_no());
jGroup1.put("time_no",ticketAll.get(i).getTime_no());
jGroup1.put("ticket_no",ticketAll.get(i).getTicket_no());
jGroup1.put("branch_id",ticketAll.get(i).getBranch_id());
jGroup1.put("position_in_queue",ticketAll.get(i).getPosition_in_queue());
jsonArray.put(new Gson().toJson(jGroup1, Map.class));
}
String str = POST(UrlPost,"");
}
public String POST(String url, String json){
enableStrictMode();
HttpResponse response = null;
HttpClient httpclient= null;
httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet();
try {
request.setURI(new URI("IP"));
response = httpclient.execute(request);
}
catch (URISyntaxException e) {
e.printStackTrace();
}
catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
EntityUtils.consumeQuietly(response.getEntity());
InputStream inputStream = null;
String result = "";
try {
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost();
// 4. convert JSONObject to JSON to String
json = jsonArray.toString();
json = json.replace("\\","").replace("\"{" ,"{").replace("}\"" ,"}");
String userName ="admin";
String password = "******";
String base64EncodedCredentials = "Basic " + Base64.encodeToString(
(userName + ":" + password).getBytes(),
Base64.NO_WRAP);
httpPost.setHeader("Authorization", base64EncodedCredentials);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("TenantId", TenantId));
nameValuePairs.add(new BasicNameValuePair("JsonData", json));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpPost.setURI(new URI(UrlPost));
response = httpclient.execute(httpPost);
boolean responseBody = Boolean.parseBoolean(EntityUtils.toString(response.getEntity()));
if ( (response.getStatusLine().getStatusCode()== HttpsURLConnection.HTTP_OK) && responseBody==true ){
Toast.makeText(MainActivity.this, "Updated Data", Toast.LENGTH_SHORT).show();
}
System.out.println(responseBody+" values is");
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
// 11. return result
return result;
}
public void enableStrictMode()
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
//for the time schedular functions
private Job createJob() {
int jobType = 3;
boolean isPeriodic = true;
Long miliSecondsInterval = Long.parseLong(Interval)*1000;
intervalInMillisEditText=Long.toString(miliSecondsInterval) ;
String intervalInMillisString = intervalInMillisEditText;
if (TextUtils.isEmpty(intervalInMillisString)) {
return null;
}
Long intervalInMillis = Long.parseLong(intervalInMillisString);
Job.Builder builder = new Job.Builder(JOB_ID, this, jobType, JOB_PERIODIC_TASK_TAG)
.setIntervalMillis(intervalInMillis);
if (isPeriodic) {
builder.setPeriodic(intervalInMillis);
}
return builder.build();
}
private void removePeriodicJob() {
SmartScheduler jobScheduler = SmartScheduler.getInstance(this);
if (!jobScheduler.contains(JOB_ID)) {
Toast.makeText(MainActivity.this, "No job exists with JobID: " + JOB_ID, Toast.LENGTH_SHORT).show();
return;
}
if (jobScheduler.removeJob(JOB_ID)) {
Toast.makeText(MainActivity.this, "Job successfully removed!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onJobScheduled(Context context, final Job job) {
if (job != null) {
runOnUiThread(new Runnable() {
#Override
public void run() {
// System.out.println("Shahbaz is running");
// Toast.makeText(MainActivity.this, "Job: " + job.getJobId() + " scheduled!", Toast.LENGTH_SHORT).show();
CallApi();
getTableData();
}
});
Log.d(TAG, "Job: " + job.getJobId() + " scheduled!");
}
}
//nevigation
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.newItem1) {
Intent intent = new Intent(this,SecondActivity.class);
startActivity(intent);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void onResetSchedulerClick(MenuItem item) {
SmartScheduler smartScheduler = SmartScheduler.getInstance(getApplicationContext());
smartScheduler.removeJob(JOB_ID);
Toast.makeText(this, "Service has been Stoped!", Toast.LENGTH_SHORT).show();
// Button btnstart = (Button) findViewById(R.id.button);
// btnstart.setVisibility(View.VISIBLE);
// smartJobButton.setText(getString(R.string.schedule_job_btn));
// smartJobButton.setEnabled(true);
// smartJobButton.setAlpha(1.0f);
}
}
Hello all i have a search activity into my app that works good if i try to search an item by tiping a text keyword but if i try to search an item that also contain a number app crash. For example if i try to search the text "home" search works good but if i search "home 3" app crash. The error is : exception-illegal-character-in-query-at-index I want that the search works good also by typing a text or a text + number exc..
Thank you
IMPORTANT :
the search activity call an encoded url, "ADSEARCH_URL"
public static final String ADSEARCH_URL="https://gjeme.com/apps/menjehere/index.php?action=searchAd&categoryId=%s&adcity=%s&q=%s";
This is the search activity :
public class SearchActivity extends AppCompatActivity {
Toolbar toolbar;
ListView lsv;
String categoryId,keyword,city;
ProgressDialog progressBar;
List<CatAdd> catAddList;
CateAdDisplayAdapter adapter;
Typeface typeface;
#SuppressLint("NewApi") #Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activty_search);
toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null) {
toolbar.setTitle("Browse Ads");
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
getActionBarTextView();
typeface = Typeface.createFromAsset(getAssets(), "fonts/GandhiSerif- Bold.otf");
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
lsv = (ListView)findViewById(R.id.listView1);
catAddList = new ArrayList<CatAdd>();
categoryId = getIntent().getExtras().getString("categoryId", "0");
keyword = getIntent().getExtras().getString("keyword","keyword");
city = getIntent().getExtras().getString("city","city");
new SearchList().execute();
lsv.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Intent intent = new Intent(getApplicationContext(), BrowseAdsDetailActivity.class);
intent.putExtra("adId", String.valueOf(catAddList.get(arg2).getAddid()));
startActivity(intent);
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if(id==android.R.id.home)
{
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
}
private TextView getActionBarTextView() {
TextView titleTextView = null;
try {
Field f = toolbar.getClass().getDeclaredField("mTitleTextView");
f.setAccessible(true);
titleTextView = (TextView)f.get(toolbar);
titleTextView.setTypeface(typeface);
} catch (NoSuchFieldException e) {
} catch (IllegalAccessException e) {
}
return titleTextView;
}
class SearchList extends AsyncTask<Void, Void, Void>
{
String jsonStr = null;
CustomProgressDialog cd = new CustomProgressDialog();
#Override
protected void onPreExecute() {
super.onPreExecute();
cd.showdialog(SearchActivity.this, "Loading...");
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler sh = new ServiceHandler();
jsonStr = sh.makeServiceCall(String.format(Constants.ADSEARCH_URL,categoryId,city,keyword) , ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray contacts = jsonObj.getJSONArray(Constants.TAG);
for (int i = contacts.length()-1; i > -1; i--) {
JSONObject c = contacts.getJSONObject(i);
String adId = c.getString(Constants.CAT_ADID);
String adTitle = c.getString(Constants.CAT_ADTITLE);
String adDes = c.getString(Constants.CAT_ADDES);
String adCreatedAt = c.getString("adCreatedAt");
String adcity= c.getString(Constants.CAT_CITY);
String adPrise= c.getString(Constants.CAT_PRICE);
JSONArray arrImages=c.getJSONArray("images");
ArrayList<String> imgArray=new ArrayList<String>();
for(int j=0;j<arrImages.length();j++)
{
JSONObject imgObj=arrImages.getJSONObject(j);
if(imgObj.has("imageName"))
{
imgArray.add(imgObj.getString("imageName"));
}
}
CatAdd v=new CatAdd();
v.setAddid(Integer.parseInt(adId));
v.setAdTitle(adTitle);
v.setAdDesc(adDes);
v.setAdCreatedAt(adCreatedAt);
v.setAdPrice(adPrise);
v.setImglist(imgArray);
v.setAdCity(adcity);
catAddList.add(v);
}
} 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);
cd.dismissdialog();
adapter = new CateAdDisplayAdapter(getApplicationContext(), catAddList);
lsv.setAdapter(adapter);
}
}
}
I think there isn't any problem with alpha-numeric characters here, but the SPACE is created one, while you are adding the text to URL.
Replace space(es) of searched keyword with %20 and hopefully you will find it fine.
Hello guys i have an issue with my search activit. If i try to search an item for example (iphone 6) and type only "iphone" or "6" or only "i" and other exc... the search works god, but if i put the entire name of the item in this case : iphone 6 , apps crash.
This is the code :
public class SearchActivity extends AppCompatActivity {
Toolbar toolbar;
ListView lsv;
String categoryId,keyword,city;
ProgressDialog progressBar;
List<CatAdd> catAddList;
CateAdDisplayAdapter adapter;
Typeface typeface;
#SuppressLint("NewApi") #Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activty_search);
toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null) {
toolbar.setTitle("Browse Ads");
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
getActionBarTextView();
typeface = Typeface.createFromAsset(getAssets(), "fonts/GandhiSerif-Bold.otf");
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
lsv = (ListView)findViewById(R.id.listView1);
catAddList = new ArrayList<CatAdd>();
categoryId = getIntent().getExtras().getString("categoryId", "0");
keyword = getIntent().getExtras().getString("keyword","keyword");
city = getIntent().getExtras().getString("city","city");
new SearchList().execute();
lsv.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Intent intent = new Intent(getApplicationContext(), BrowseAdsDetailActivity.class);
intent.putExtra("adId", String.valueOf(catAddList.get(arg2).getAddid()));
startActivity(intent);
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if(id==android.R.id.home)
{
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
}
private TextView getActionBarTextView() {
TextView titleTextView = null;
try {
Field f = toolbar.getClass().getDeclaredField("mTitleTextView");
f.setAccessible(true);
titleTextView = (TextView)f.get(toolbar);
titleTextView.setTypeface(typeface);
} catch (NoSuchFieldException e) {
} catch (IllegalAccessException e) {
}
return titleTextView;
}
class SearchList extends AsyncTask<Void, Void, Void>
{
String jsonStr = null;
CustomProgressDialog cd = new CustomProgressDialog();
#Override
protected void onPreExecute() {
super.onPreExecute();
cd.showdialog(SearchActivity.this, "Loading...");
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler sh = new ServiceHandler();
jsonStr = sh.makeServiceCall(String.format(Constants.ADSEARCH_URL,categoryId,city,keyword), ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray contacts = jsonObj.getJSONArray(Constants.TAG);
for (int i = contacts.length()-1; i > -1; i--) {
JSONObject c = contacts.getJSONObject(i);
String adId = c.getString(Constants.CAT_ADID);
String adTitle = c.getString(Constants.CAT_ADTITLE);
String adDes = c.getString(Constants.CAT_ADDES);
String adCreatedAt = c.getString("adCreatedAt");
String adcity= c.getString(Constants.CAT_CITY);
String adPrise= c.getString(Constants.CAT_PRICE);
JSONArray arrImages=c.getJSONArray("images");
ArrayList<String> imgArray=new ArrayList<String>();
for(int j=0;j<arrImages.length();j++)
{
JSONObject imgObj=arrImages.getJSONObject(j);
if(imgObj.has("imageName"))
{
imgArray.add(imgObj.getString("imageName"));
}
}
CatAdd v=new CatAdd();
v.setAddid(Integer.parseInt(adId));
v.setAdTitle(adTitle);
v.setAdDesc(adDes);
v.setAdCreatedAt(adCreatedAt);
v.setAdPrice(adPrise);
v.setImglist(imgArray);
v.setAdCity(adcity);
catAddList.add(v);
}
} 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);
cd.dismissdialog();
adapter = new CateAdDisplayAdapter(getApplicationContext(), catAddList);
lsv.setAdapter(adapter);
}
}
Assuming you are making an api call:
You should encode parameters in your url.
String query = URLEncoder.encode("phone 6", "utf-8");
String url = "http://myurl.com/search?q=" + query;
The result would be: http://myurl.com/search?q=phone%206
I have a project that
Gets user details
Sends user details to a MySQL server
Now I want to make my EditTexts not empty .
Or its characters are more than 3.
My code works when a user sends invalid or empty details.
But when all EditTexts are filled correctly my application show a ForceStop error.
public class Register extends Activity {
public EditText name, lastName, phoneNumber, email, username, password, namee, lastNamee, phoneNumberr, usernamee, passwordd;
private FButton reg_btn_login;
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "http://mojtabaapp.esy.es/register.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
// baresi edit text ha
public boolean AyaVorodYSahihBood() {
namee = (EditText) findViewById(R.id.ET_name);
lastNamee = (EditText) findViewById(R.id.ET_famili);
phoneNumberr = (EditText) findViewById(R.id.ET_phone);
usernamee = (EditText) findViewById(R.id.user);
passwordd = (EditText) findViewById(R.id.pass);
boolean n, l, ph, u, p;
n = name.getText().toString().length() > 3;
l = lastNamee.getText().toString().length() > 3;
ph = phoneNumberr.getText().toString().length() == 11;
u = usernamee.getText().toString().length() > 5;
p = passwordd.getText().toString().length() > 5;
if (n | l | ph | u | p) {
return false;
} else return true;
}
private boolean isNetworkConnected() { // check internet connection
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni == null) {
// There are no active networks.
return false;
} else return true;
}
public void NamayeshBedeDialog() {
new MaterialDialog.Builder(this)
.title(string.title_dialog)
.content(string.dialog_content)
.positiveText(string.bashe)
// .negativeText(string.mikham_brm)
.show();
new MaterialDialog.Builder(this)
.callback(new MaterialDialog.ButtonCallback() {#Override
public void onPositive(MaterialDialog dialog) {
// dialog.dismiss();
}#Override
public void onNegative(MaterialDialog dialog) {
//finish();
}
});
}
//method namayesh dialog email eshteba
public void Namayesh_dialog_email_eshteba() {
AlertDialog.Builder abb = new AlertDialog.Builder(this);
abb.setTitle(R.string.title_dialog);
abb.setMessage(R.string.Email_eshteba_ast);
abb.setPositiveButton(talash_mojadad, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
startActivity(getIntent());
}
});
abb.setIcon(android.R.drawable.ic_dialog_alert);
abb.show();
}
//method namayesh shomare eshteba
public void Namayesh_dialog_shomare_eshteba() {
AlertDialog.Builder abbb = new AlertDialog.Builder(this);
abbb.setTitle(R.string.title_dialog);
abbb.setMessage(R.string.phonenumber_is_incorrect);
abbb.setPositiveButton(talash_mojadad, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
startActivity(getIntent());
}
});
abbb.setIcon(android.R.drawable.ic_dialog_alert);
abbb.show();
}#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
// tarif ha
name = (com.rengwuxian.materialedittext.MaterialEditText) findViewById(R.id.ET_name);
lastName = (com.rengwuxian.materialedittext.MaterialEditText) findViewById(R.id.ET_famili);
phoneNumber = (com.rengwuxian.materialedittext.MaterialEditText) findViewById(R.id.ET_phone);
reg_btn_login = (FButton) findViewById(R.id.reg_btn_login);
email = (com.rengwuxian.materialedittext.MaterialEditText) findViewById(R.id.ET_mail);
// aya addres email sahih mibashad ?
reg_btn_login.setOnClickListener(new OnClickListener() {#Override
public void onClick(View v) {
if (isNetworkConnected() == false) {
NamayeshBedeDialog();
return;
}
if (AyaVorodYSahihBood()) {
NamayeshBedeDialog();
return;
}
new CreateUser().execute();
}
});
if (isNetworkConnected() == false) {
NamayeshBedeDialog();
}
}
class CreateUser extends AsyncTask < String, String, String > {
boolean failure = false;#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Register.this);
pDialog.setMessage("..???? ??? ??? ????");
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 = name.getText().toString();
String LASTNAME = lastName.getText().toString();
String MAIL = email.getText().toString();
int PHONE = Integer.parseInt(phoneNumber.getText().toString());
int cash = 0;
try {
// Building Parameters
List < NameValuePair > params = new ArrayList < NameValuePair > ();
params.add(new BasicNameValuePair("username", NAME));
params.add(new BasicNameValuePair("password", LASTNAME));
params.add(new BasicNameValuePair("emailaddres", MAIL));
params.add(new BasicNameValuePair("phonenumber", String.valueOf(PHONE)));
params.add(new BasicNameValuePair("usercash", String.valueOf(cash)));
Log.d("request!", "starting");
//Posting user data to script
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// full json response
Log.d("Login attempt", json.toString());
// jon 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;
}
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();
}
}
}#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_register, menu);
return true;
}#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
How to create SharedPreferences with set visibility in login if the user is successfully login the button will be logout and the login will be gone
public class Login extends ActionBarActivity implements View.OnClickListener{
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
private static String url_check_login = "";
private static final String TAG_SUCCESS = "success";
Context cont=this;
EditText uname, pword;
Boolean nega = false;
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_user);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
uname = (EditText) findViewById(R.id.uname);
pword = (EditText) findViewById(R.id.pword);
Button login = (Button)findViewById(R.id.btnLogin);
login.setOnClickListener(this);
Button register = (Button)findViewById(R.id.btnRegister);
register.setOnClickListener(this);
}
#Override
public void onClick(View v)
{
final int id = v.getId();
switch (id) {
case R.id.btnLogin:
new SubmitLogin().execute();
break;
case R.id.btnRegister:
Intent i = new Intent (this, Registration.class);
startActivity(i);
finish();
break;
// even more buttons here
}
}
class SubmitLogin extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Logging In ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", uname.getText().toString()));
params.add(new BasicNameValuePair("pass", pword.getText().toString()));
JSONObject json = jsonParser.makeHttpRequest(url_check_login, "POST", params);
Log.d("Create Response", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
nega = false;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = prefs.edit();
editor.putString("username", uname.getText().toString());
editor.commit();
Intent gotoLogs = new Intent(cont, MainActivity.class);
startActivity(gotoLogs);
finish();
} else {
nega = true;
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
if (nega) {
new AlertDialog.Builder(cont)
.setTitle("Login Failed")
.setMessage("Wrong Username or Password")
.setNegativeButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
//Close current activity
startActivity(new Intent(this,MainActivity.class));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
To place info into SharedPreferences you should write following:
SharedPreferences sp = getSharedPreferences(PREFERNCES_FILE, MODE_PRIVATE);
sp.edit().putString(PREFERENCES_LOGIN, login).apply();
Variables PREFERNCES_FILE and PREFERENCES_LOGIN should be defined as String:
public static final String PREFERNCES_FILE = "my_preferences_file";
public static final String PREFERENCES_LOGIN = "login";
On logout there should be:
sp.edit().remove(PREFERENCES_LOGIN).apply();
Then to check if there is allready some info call:
boolean isLogged = sp.contains(PREFERENCES_LOGIN);
Then just set needed visibility:
login.setVisibility(isLogged ? View.GONE : View.VISIBLE);
UPDATE
Ok, here is example. This code should be in onCreate:
SharedPreferences sp = getSharedPreferences(PREFERNCES_FILE, MODE_PRIVATE);
boolean isLogged = sp.contains(PREFERENCES_LOGIN);
Button login = (Button)findViewById(R.id.btnLogin);
login.setVisibility(isLogged ? View.GONE : View.VISIBLE);
login.setOnClickListener(this);
Button logout = (Button)findViewById(R.id.btnLogout);
logout.setVisibility(isLogged ? View.VISIBLE : View.GONE);
logout.setOnClickListener(this);
And there should be button in your login_user xml with btnLogout id.
In onClick should be:
#Override
public void onClick(View v)
{
final int id = v.getId();
switch (id) {
case R.id.btnLogin:
SharedPreferences sp = getSharedPreferences(PREFERNCES_FILE, MODE_PRIVATE);
sp.edit().putString(PREFERENCES_LOGIN, login).apply();
findViewById(R.id.btnLogin).setVisibility(View.GONE);
findViewById(R.id.btnLogout).setVisibility(View.VISIBLE);
//another actions after login
break;
case R.id.btnLogout:
SharedPreferences sp = getSharedPreferences(PREFERNCES_FILE, MODE_PRIVATE);
sp.edit().remove(PREFERENCES_LOGIN).apply();
findViewById(R.id.btnLogin).setVisibility(View.VISIBLE);
findViewById(R.id.btnLogout).setVisibility(View.GONE);
//another actions after logout
break;
// even more buttons here
}
}
In login variable should be login data - I don't know where you should get it.