I have a android spinner like this
First one is item name and second one is their respective item id.I want to send respective item id to server when item name is selected and I don't want to desplay item id also.How to resolve this here is my code:
public class Form extends BaseActivity implements AdapterView.OnItemClickListener {
private static final String REGISTER_URL = "http://url/Service.asmx/GenerateTicket";
public static final String PREFS_NAME = "MyPrefsFile";
public static final String CUSTOMERID = "customerId";
public static final String USERNAME = "name";
public static final String HOUSENO = "houseNo";
public static final String LOCALITY = "areaName";
public static final String SERVICE = "serviceId";
public static final String MOBILE = "mobile";
public static final String EMAIL = "email";
public static final String PROBLEM = "jobBrief";
private ProgressDialog pDialog;
Spinner spin;
// flag for Internet connection status
Boolean isInternetPresent = false;
// Connection detector class
ConnectionDetector cd;
// ArrayList<String> listItems = new ArrayList<>();
// ArrayAdapter<String> adapter;
private List<Item> customerList = new ArrayList<Item>();
private SpinAdapter adapter;
private List<Item> items;
private EditText editname, houseNo, mobile, email, problem;
Spinner service_need;
AutoCompleteTextView autoCompView;
String obj;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getLayoutInflater().inflate(R.layout.activity_form, frameLayout);
autoCompView = (AutoCompleteTextView) findViewById(R.id.colony);
autoCompView.setAdapter(new GooglePlacesAutocompleteAdapter(this, R.layout.list_item));
autoCompView.setOnItemClickListener(this);
editname = (EditText) findViewById(R.id.name);
houseNo = (EditText) findViewById(R.id.houseNo);
//
mobile = (EditText) findViewById(R.id.mobile);
email = (EditText) findViewById(R.id.email);
problem = (EditText) findViewById(R.id.problem);
Button submit = (Button) findViewById(R.id.submit);
pDialog = new ProgressDialog(this);
cd = new ConnectionDetector(getApplicationContext());
// get Internet status
isInternetPresent = cd.isConnectingToInternet();
//
assert submit != null;
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (editname.getText().toString().trim().equals("")) {
Toast.makeText(getApplicationContext(),
"Please enter your name", Toast.LENGTH_SHORT)
.show();
} else if (houseNo.toString().trim().equals("")) {
Toast.makeText(Form.this, "Please enter your house no", Toast.LENGTH_SHORT).show();
} else if (autoCompView.toString().trim().equals("")) {
Toast.makeText(Form.this, "Please enter your locality", Toast.LENGTH_SHORT).show();}
// } else if (service_need.getSelectedItem().toString().trim().equals("Select Service")) {
// Toast.makeText(Form.this, "Please Select item", Toast.LENGTH_SHORT).show();
//
// }
else if (mobile.toString().trim().equals("")) {
Toast.makeText(Form.this, "Please enter your mobile number", Toast.LENGTH_SHORT).show();
}
else if (mobile.getText().length() < 10) {
Toast.makeText(getApplicationContext(),
"Please enter valid mobile number", Toast.LENGTH_SHORT)
.show();
}
else if (problem.toString().trim().equals("")) {
Toast.makeText(Form.this, "Please describe your problem", Toast.LENGTH_SHORT).show();
}
else if (!email.getText().toString().trim().equals(""))
{
if (!android.util.Patterns.EMAIL_ADDRESS.matcher(
email.getText().toString().trim()).matches()) {
Toast.makeText(getApplicationContext(),
"Please enter valid e-mail id", Toast.LENGTH_SHORT)
.show();
}
else {
if (isInternetPresent) {
registerUser();
pDialog.setMessage("Loading...");
pDialog.show();
Toast.makeText(getApplicationContext(),
"connecting...", Toast.LENGTH_SHORT)
.show();
} else {
Toast.makeText(Form.this, "Unable to connect the server, please check your data settings", Toast.LENGTH_LONG)
.show();
}
}
}
else {
// Do your stuff
if (isInternetPresent) {
registerUser();
pDialog.setMessage("Loading...");
pDialog.show();
Toast.makeText(getApplicationContext(),
"connecting...", Toast.LENGTH_SHORT)
.show();
}
else {
Toast.makeText(Form.this, "Unable to connect the server, please check your data settings", Toast.LENGTH_LONG)
.show();
}
}
}
});
//
spin = (Spinner) findViewById(R.id.service_need);
adapter = new SpinAdapter(this, customerList);
spin.setAdapter(adapter);
}
private void registerUser() {
final SharedPreferences mSharedPreference= PreferenceManager.getDefaultSharedPreferences(getBaseContext());
final String value=(mSharedPreference.getString("customerId", "Default_Value"));
final String customer_id = value.trim();
final String username = editname.getText().toString().trim();
final String house = houseNo.getText().toString().trim();
final String local_area = autoCompView.getText().toString().trim();
**Something wrong with this line**
**final String service = spin.getSelectedItem().toString().trim();**
final String mobile_no = mobile.getText().toString().trim();
final String email_id = email.getText().toString().trim();
final String prob = problem.getText().toString().trim();
Toast.makeText(Form.this, username.toString(), Toast.LENGTH_LONG).show();
Toast.makeText(Form.this, service.toString(), Toast.LENGTH_LONG).show();
Toast.makeText(Form.this, local_area.toString(), Toast.LENGTH_LONG).show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, REGISTER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
hidePDialog();
try {
//String result="";
//Do it with this it will work
JSONArray jsonarray = new JSONArray(response);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject person = jsonarray.getJSONObject(i);
String excep = person.getString("Exception");
String message1 = person.getString("Message");
String job = person.getString("JobNo");
if (excep.equalsIgnoreCase("True")) {
Toast.makeText(Form.this, excep, Toast.LENGTH_LONG)
.show();
} else {
Toast.makeText(Form.this, excep, Toast.LENGTH_LONG)
.show();
editname.setText("");
// if email and mb is valid than login
Intent i1 = new Intent(Form.this, Suceessful.class);
i1.putExtra("job_id", job);
startActivity(i1);
finish();
Toast.makeText(Form.this, excep.toString(), Toast.LENGTH_LONG).show();
Toast.makeText(Form.this, message1.toString(), Toast.LENGTH_LONG).show();
Toast.makeText(Form.this, job.toString(), Toast.LENGTH_LONG).show();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Form.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put(CUSTOMERID,customer_id);
params.put(USERNAME, username);
params.put(HOUSENO, house);
params.put(LOCALITY, local_area);
params.put(SERVICE, service);
params.put(MOBILE, mobile_no);
params.put(EMAIL, email_id);
params.put(PROBLEM, prob);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
adapter.notifyDataSetChanged();
}
protected Void doInBackground(Void... params) {
InputStream is = null;
String result = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://url/Service.asmx/GetServiceList");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// Get our response as a String.
is = entity.getContent();
} catch (IOException e) {
e.printStackTrace();
}
//convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"));
String line = null;
while ((line = reader.readLine()) != null) {
result += line;
}
is.close();
//result=sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
// parse json data
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject obj = jArray.getJSONObject(i);
Item customer = new Item();
customer.setiD(obj.getString("ServiceId"));
customer.setsText(obj.getString("ServiceName"));
// adding movie to movies array
customerList.add(customer);
}
} catch (JSONException e) {
e.printStackTrace();
}
// adapter.notifyDataSetChanged();
return null;
}
protected void onPostExecute(Void result) {
customerList.addAll(items);
adapter.notifyDataSetChanged();
}
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
// Inflate menu to add items to action bar if it is present.
inflater.inflate(R.menu.main, menu);
MenuItem item = menu.findItem(R.id.refresh);
item.setVisible(false);
return true;
}
}
There are several ways to achieve this. I think the simplest way is to create a model class for your spinner item.
public class Item implements Serializable {
public String sText;
public int iD;
public int getiD() {
return iD;
}
public void setiD(int iD) {
this.iD = iD;
}
public Item(String sText, int iD) {
this.sText = sText;
this.iD=iD;
}
public String getsText() {
return sText;
}
public void setsText(String sText) {
this.sText = sText;
}
#Override
public boolean equals(Object o) {
Item item = (Item) o;
if (item.getiD()==iD)
return true;
else
return false;
}
#Override
public String toString() {
return this.sText; // What to display in the Spinner list.
}
}
In the activity class you can create an ArrayAdapter.
private ArrayAdapter adapter;
private List<Item> items;
Inside onCreate initialize list and adapter and set the adapter.
items= new ArrayList<>();
adapter = new ArrayAdapter<Item>(getActivity(), android.R.layout.simple_spinner_item, items);
service_need.setAdapter(adapter);
Replace json parsing like this:
// parse json data
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsonObject = jArray.getJSONObject(i);
// add interviewee name to arraylist
items.add(new Item(jsonObject.getString("ServiceName"),jsonObject.getString("ServiceId")));
}
} catch (JSONException e) {
e.printStackTrace();
}
Then call adapter.notifyDataSetChanged() inside onPostExecute().
In the onClick, you can fetch the customer ID from the spinner.
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String customer_id=customerList.get(spinner_cat.getSelectedItemPosition()).getiD();
To hide the Id you must not add it to the array you are passing to spinner.
Use a structure to create objects with properties name and id.
private static class Items
{
public String name;
public String id;
}
You can add setters and getters methods.
Create a list of Items object. Set each object values for name and id from server.
Create an array of strings for spinner consisting of names of Items objects in order.
On selection event of spinner, get the id of Items object in the list from selected position and use it to send to server.
Related
I am new to android. I need to pass values from the spinner to asynctask as an parameter and till now I am successful in showing the results in spinner successfully. Now i need to pass the selected value from the spinner to another activity on a button click (as an parameter to asynctask). Below is the code. Thanks in advance.
BackgroundFetchWorker.java:
public class BackgroundFetchWorker extends AsyncTask<String,Void,String> {
String json_string;
ProgressDialog progressDialog;
Context context;
BackgroundFetchWorker(Context ctx)
{
context = ctx;
}
#Override
protected String doInBackground(String... params) {
String type2 = params[0];
String student_fetch_url = "http://pseudoattendance.pe.hu/studentFetch.php";
if (type2.equals("fetchSubject")) {
try {
String semester = params[1];
String stream = params[2];
URL url = new URL(student_fetch_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoOutput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("semester", "UTF-8") + "=" + URLEncoder.encode(semester, "UTF-8")
+ URLEncoder.encode("stream","UTF-8")+"="+URLEncoder.encode(stream,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
String result = " ";
String line = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(context);
progressDialog.setTitle("Fetching Data....");
progressDialog.setMessage("This may take a while..");
progressDialog.show();
}
#Override
protected void onPostExecute(String result) {
progressDialog.dismiss();
String s = result.trim();
if(s.equals("{\"result\":[]}")){
Toast.makeText(context, "ERROR OCCURED", Toast.LENGTH_SHORT).show();
}
else {
json_string = result;
Intent i = new Intent(context, TakeAttendanceActivity.class);
i.putExtra("studentdata", json_string);
context.startActivity(i);
Toast.makeText(context, "Success", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
FacultyWelcomeActivity.java:
public class FacultyWelcomeActivity extends AppCompatActivity implements Spinner.OnItemSelectedListener{
String JSON_STRING;
JSONObject jsonObject;
JSONArray jsonArray;
ContactAdapter contactAdapter;
ListView listView;
//Declaring an Spinner
private Spinner spinner;
private Spinner spinner1;
//An ArrayList for Spinner Items
private ArrayList<String> students;
private ArrayList<String> stream;
//JSON Array
private JSONArray result;
private JSONArray result1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_faculty_welcome);
//Initializing the ArrayList
students = new ArrayList<String>();
stream = new ArrayList<String>();
//Initializing Spinner
spinner = (Spinner) findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String semesters= parent.getItemAtPosition(position).toString();
String stream= parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
spinner1 = (Spinner) findViewById(R.id.spinner1);
//Adding an Item Selected Listener to our Spinner
//As we have implemented the class Spinner.OnItemSelectedListener to this class iteself we are passing this to setOnItemSelectedListener
getData();
getData1();
listView = (ListView) findViewById(R.id.lectureList);
contactAdapter = new ContactAdapter(this, R.layout.rowlayout);
listView.setAdapter(contactAdapter);
JSON_STRING = getIntent().getExtras().getString("JSON Data");
try {
jsonObject = new JSONObject(JSON_STRING);
jsonArray = jsonObject.getJSONArray("result");
int count = 0;
String sub1, sub2, sub3, sub4;
while (count < jsonArray.length()) {
JSONObject JO = jsonArray.getJSONObject(count);
sub1 = JO.getString("fname");
sub2 = JO.getString("lname");
sub3 = JO.getString("id");
sub4 = JO.getString("email");
Contacts contacts = new Contacts(sub1, sub2, sub3, sub4);
contactAdapter.add(contacts);
count++;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public void fetchSubject(View view) {
String type2 = "fetchSubject";
String spinnerdata = spinner.getSelectedItem().toString();
String spinner1data = spinner1.getSelectedItem().toString();
BackgroundFetchWorker background = new BackgroundFetchWorker(this);
background.execute(type2,spinnerdata,spinner1data);
}
private void getData1(){
StringRequest stringRequest = new StringRequest(Config2.DATA_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
result1 = j.getJSONArray(Config2.JSON_ARRAY);
getStudents1(result1);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void getData(){
StringRequest stringRequest = new StringRequest(Config.DATA_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
result = j.getJSONArray(Config.JSON_ARRAY);
getStudents(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void getStudents(JSONArray j){
for(int i=0;i<j.length();i++){
try {
//Getting json object
JSONObject json = j.getJSONObject(i);
students.add(json.getString(Config.TAG_SEMESTER));
} catch (JSONException e) {
e.printStackTrace();
}
}
spinner.setAdapter(new ArrayAdapter<String>(FacultyWelcomeActivity.this, android.R.layout.simple_spinner_dropdown_item, students));
}
private void getStudents1(JSONArray j){
//Traversing through all the items in the json array
for(int i=0;i<j.length();i++){
try {
//Getting json object
JSONObject json = j.getJSONObject(i);
//Adding the name of the student to array list
stream.add(json.getString(Config2.TAG_STREAM));
} catch (JSONException e) {
e.printStackTrace();
}
}
spinner1.setAdapter(new ArrayAdapter<String>(FacultyWelcomeActivity.this, android.R.layout.simple_spinner_dropdown_item, stream));
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//check which spinner triggered the listener
}
#Override
public void onNothingSelected(AdapterView<?> parent) {}}
You are passing parameters to doInBackground() this way:
background.execute("your string");
Now the string "your string" will be the parameter within doInBackground() callback:
#Override
protected String doInBackground(String... params) {
String type2 = params[0]; // type2 == "your string"
...
}
See docs for more info.
I am getting my content from json through server.I have two TextView and one ImageView in my layout.i have written the content from json to a file. but i not able to set my data while offline
I am getting the data from a file also.
MainActivity.java:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private Context context;
private NavigationView mNavigationView;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
NewsAdapter adapter;
ArrayList<News> Newslist;
private Toolbar mToolbar;
private ProgressDialog pDialog;
private String TAG = MainActivity.class.getSimpleName();
private static String url = "https://www.amrita.edu/amrita_api/v1/news_android.jsonp";
String image;
String imageurl;
ArrayList<HashMap<String, String>> arraylist;
// ArrayList<String> newsList = new ArrayList<String>();
WebView descWView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_json);
Newslist = new ArrayList<News>();
context=getApplicationContext();
//initViews();
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle(R.string.title);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setIcon(R.drawable.app_icon);
initViews();
initContentWebView();
setUpNavDrawer();
new GetContacts().execute();
}
private void initViews(){
mNavigationView = (NavigationView) findViewById(R.id.navigation_view);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
}
void initContentWebView(){
String htmlText = " %s ";
// ArrayList<String> myData = newsList;
// descWView = (WebView) findViewById(R.id.content_wview);
// String htmlData= "<html><body style='text-align:justify;font-size:"+getResources().getInteger(R.integer.main_text)+"px'><p>'sajhdsakjc;osalcjklsx'</p>"+myData.toString()+"</body></Html >";
//descWView.getSettings().setDefaultTextEncodingName("utf-8");
// descWView.loadData(htmlData, "text/html", "utf-8");
// descWView.loadDataWithBaseURL(String.format(htmlText, htmlData), String.valueOf(myData), "text/html", "UTF-8", String.format(htmlText, htmlData));
// descWView.s(myData);
}
private void setUpNavDrawer() {
mDrawerToggle=new ActionBarDrawerToggle(this,mDrawerLayout,mToolbar,R.string.drawer_open,R.string.drawer_close);
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
mNavigationView.setNavigationItemSelectedListener(this);
}
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
String item=menuItem.getTitle().toString();
String dPath=menuItem.getTitleCondensed().toString();
if(item.equals("News")){
//this.finish();
mDrawerLayout.closeDrawers();
Intent intent = new Intent(context, MainActivity.class);
startActivity(intent);
this.finish();
//Toast.makeText(getApplicationContext(), "god", Toast.LENGTH_SHORT).show();
}
else if(item.equals("Events")){
mDrawerLayout.closeDrawers();
Intent intent = new Intent(context, EventActivity.class);
startActivity(intent);
this.finish();
Toast.makeText(getApplicationContext(), "god1", Toast.LENGTH_SHORT).show();
}
else if(item.equals("Latest Publications")){
mDrawerLayout.closeDrawers();
Toast.makeText(getApplicationContext(), "god2", Toast.LENGTH_SHORT).show();
} else if(item.equals("Students Achivements")){
mDrawerLayout.closeDrawers();
Toast.makeText(getApplicationContext(), "god3", Toast.LENGTH_SHORT).show();
}
else if(item.equals("Important Announcements")){
mDrawerLayout.closeDrawers();
Toast.makeText(getApplicationContext(), "god4", Toast.LENGTH_SHORT).show();
}
else if(item.equals("Research")){
mDrawerLayout.closeDrawers();
Intent intent = new Intent(context, ResearchActivity.class);
startActivity(intent);
this.finish();
//Toast.makeText(getApplicationContext(), "god5", Toast.LENGTH_SHORT).show();
}
else if(item.equals("Ranking")){
mDrawerLayout.closeDrawers();
//Toast.makeText(getApplicationContext(), "god6", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, RankingActivity.class);
startActivity(intent);
this.finish();
}
else if(item.equals("International")){
mDrawerLayout.closeDrawers();
//Toast.makeText(getApplicationContext(), "god7", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, InternationalActivity.class);
startActivity(intent);
this.finish();
}
else if(item.equals("About")){
mDrawerLayout.closeDrawers();
Intent intent = new Intent(context, AboutActivity.class);
startActivity(intent);
this.finish();
// Toast.makeText(getApplicationContext(), "god8", Toast.LENGTH_SHORT).show();
}
else if(item.equals("Contact Us")) {
mDrawerLayout.closeDrawers();
// Toast.makeText(getApplicationContext(), "god9", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, ContactUs.class);
intent.putExtra("keyId", item);
intent.putExtra("descPath",dPath);
startActivity(intent);
// this.finish();
}
return true;
}
#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_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_share) {
/*Intent intent=new Intent(context,AboutActivity.class);
startActivity(intent);
return true;*/ Toast.makeText(getApplicationContext(), "msg msg", Toast.LENGTH_SHORT).show();
}
return super.onOptionsItemSelected(item);
}
/**
* Async task class to get json by making HTTP call
*/
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// arraylist = new ArrayList<HashMap<String, String>>();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
JSONArray jsonarray = null;
try {
jsonarray = new JSONArray(jsonStr);
for (int i = 0; i <jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
News news = new News();
JSONObject jsonobject = jsonarray.getJSONObject(i);
JSONObject jsonimage=jsonobject.getJSONObject("image");
//Log.d(String.valueOf(jsonimage), String.valueOf(jsonimage.length()));
String imageurl=jsonimage.getString("filename");
// System.out.println(imageurl);
// Retrive JSON Objects
news.setTitle(jsonobject.getString("title"));
news.setBody(jsonobject.getString("body"));
// news.setImage(jsonobject.getString("image"));
news.setImage(jsonimage.getString("filename"));
// Set the JSON Objects into the array
Newslist.add(news);
/*image = jsonobject.getString("image");
String title = jsonobject.getString("title");
String content = jsonobject.getString("content");
newsList.add(image);
newsList.add(title);
newsList.add(content);*/
// Log.d(newsList.get(i),"image");
// Log.d(title,"title");
// System.out.println("All MinQuantitiy"+newsList);
}
} catch (JSONException e) {
e.printStackTrace();
}
/* try {
JSONObject jsonObj = new JSONObject(jsonStr);
Log.d(jsonStr,"json");
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("news");
// looping through All Contacts
*//*for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
String email = c.getString("email");
String address = c.getString("address");
String gender = c.getString("gender");
// Phone node is JSON Object
JSONObject phone = c.getJSONObject("phone");
String mobile = phone.getString("mobile");
String home = phone.getString("home");
String office = phone.getString("office");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("id", id);
contact.put("name", name);
contact.put("email", email);
contact.put("mobile", mobile);
// adding contact to contact list
contactList.add(contact);
}*//*
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}*/
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
int sizeofarray= Newslist.size();
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setAdapter(new CustomPagerAdapter(context,sizeofarray ));
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
TextView tvtitle=(TextView)findViewById(R.id.tvtitle);
TextView tvbody=(TextView)findViewById(R.id.tvbody);
ImageView im=(ImageView)findViewById(R.id.NewsImage);
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
for(position=0;position<20;position++) {
tvtitle.setText(Newslist.get(position).getTitle());
tvbody.setText(Newslist.get(position).getBody());
// Toast.makeText(getApplicationContext(),position//, Toast.LENGTH_LONG).show();
}
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
// im.setImageResource(String.format("https://www.amrita.edu/sites/default/files/%s", Newslist.get().getImage()));
Toast.makeText(getApplicationContext(),"sizeNewslist"+sizeofarray, Toast.LENGTH_LONG).show();
// Updating parsed JSON data into ListView
/*for(int i=1;i<3;i++){
Toast.makeText(getApplicationContext(),
"aaa"+newsLists,
Toast.LENGTH_LONG)
.show();
}*/
/* ListAdapter adapter = new SimpleAdapter(
MainActivity.this, newsList,
R.layout.list_item, new String[]{"name", "email",
"content"}, new int[]{R.id.image,
R.id.title, R.id.co});
lv.setAdapter(adapter);*/
}
}
}
/* public interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, int position);
}*/
adapter class
public class CustomPagerAdapter extends PagerAdapter {
String image_url;
private Context mContext;
int size;
ArrayList<News> Newslist;
File file,file1;
StringBuffer buffer,buffer1;
DataHandler handler;
public CustomPagerAdapter(Context context, int arraysize, ArrayList<News> newslist) {
mContext = context;
size=arraysize;
Newslist=newslist;
}
#Override
public Object instantiateItem(ViewGroup collection, int position) {
ModelObject modelObject = ModelObject.values()[position];
LayoutInflater inflater = LayoutInflater.from(mContext);
ViewGroup layout = (ViewGroup) inflater.inflate(R.layout.row, collection, false);
collection.addView(layout);
TextView tvtitle=(TextView)layout.findViewById(R.id.tvtitle);
TextView tvbody=(TextView)layout.findViewById(R.id.tvbody);
ImageView im=(ImageView)layout.findViewById(R.id.NewsImage);
im.setScaleType(ImageView.ScaleType.FIT_XY);
SugarContext.init(mContext);
ConnectivityManager ConnectionManager=(ConnectivityManager)mContext.getSystemService(mContext.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo=ConnectionManager.getActiveNetworkInfo();
if(networkInfo != null && networkInfo.isConnected()==true )
{
tvtitle.setText(Html.fromHtml(Newslist.get(position).getTitle()));
tvbody.setText(Html.fromHtml(Newslist.get(position).getBody()));
image_url = "https://www.amrita.edu/sites/default/files/" + Newslist.get(position).getImage();
Picasso.with(mContext).load(image_url).into(im);
/*****************88*/
ArrayList<News> content = Newslist;
// String content="hello";
File file,file1;
FileOutputStream outputStream,outputStream1;
try {
//file = File.createTempFile("MyCache", null,getCacheDir());
file = new File(mContext.getCacheDir(), "newstitle");
file1 = new File(mContext.getCacheDir(), "newsbody");
outputStream = new FileOutputStream(file);
outputStream1 = new FileOutputStream(file1);
outputStream.write(content.get(position).getTitle().getBytes());
outputStream1.write(content.get(position).getBody().getBytes());
//outputStream.write(Integer.parseInt(content.get(position).getImage()));
// outputStream.write(Integer.parseInt(content.get(position).getTitle()));
// outputStream.write(Integer.parseInt(content.get(position).getBody()));
outputStream.close();
Log.d("filecreated", String.valueOf(file));
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader input = null;
BufferedReader input1=null;
file = null;
file1=null;
try {
file = new File(mContext.getCacheDir(), "newstitle");
file1 = new File(mContext.getCacheDir(), "newsbody");// Pass getFilesDir() and "MyFile" to read file
input = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
input1 = new BufferedReader(new InputStreamReader(new FileInputStream(file1)));
String line,line1;
buffer = new StringBuffer();
buffer1 = new StringBuffer();
while ((line = input.readLine()) != null) {
buffer.append(line);
}
while ((line1 = input1.readLine()) != null) {
buffer1.append(line1);
}
String s=buffer.toString();
String t=buffer1.toString();
//Log.d("bufferdsample", buffer.toString());
Toast.makeText(mContext, "asas"+s, Toast.LENGTH_LONG).show();
Toast.makeText(mContext, "body"+t, Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
/*****************************88*/
/* try {
handler = new DataHandler(mContext);
handler.open();
} catch (Exception e) {
Toast.makeText(mContext, "exc " + e,
Toast.LENGTH_SHORT).show();
}
handler.insertData(Newslist.get(position).getImage(),Newslist.get(position).getTitle(),Newslist.get(position).getBody());
*/
Toast.makeText(mContext, "Network Available", Toast.LENGTH_LONG).show();
}
else
{
BufferedReader input = null;
BufferedReader input1=null;
file = null;
file1=null;
try {
file = new File(mContext.getCacheDir(), "newstitle");
file1 = new File(mContext.getCacheDir(), "newsbody");// Pass getFilesDir() and "MyFile" to read file
input = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
input1 = new BufferedReader(new InputStreamReader(new FileInputStream(file1)));
String line,line1;
buffer = new StringBuffer();
buffer1 = new StringBuffer();
while ((line = input.readLine()) != null) {
buffer.append(line);
}
while ((line1 = input1.readLine()) != null) {
buffer1.append(line1);
}
String s=buffer.toString();
String t=buffer1.toString();
//Log.d("bufferdsample", buffer.toString());
Toast.makeText(mContext, "asas"+s, Toast.LENGTH_LONG).show();
Toast.makeText(mContext, "body"+t, Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(mContext, "Network Available", Toast.LENGTH_LONG).show();
/* image_url = "https://www.amrita.edu/sites/default/files/" + Newslist.get(position).getImage();
Picasso.with(mContext).load(image_url).into(im);*/
}
/* String fileName="cachefile";
try {
cacheThis.writeObject(mContext, fileName, Newslist);
} catch (IOException e) {
e.printStackTrace();
}
try {
Newslist.addAll((List<News>) cacheThis.readObject(mContext, fileName));
Log.d("aaasasa", String.valueOf(Newslist));
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}*/
// ImageLoader class instance
// whenever you want to load an image from url
// call DisplayImage function
// url - image url to load
// loader - loader image, will be displayed before getting image
// image - ImageView
//im.setImageBitmap(getBitmapFromURL("https://3.bp.blogspot.com/-yEE6FqiglKw/VeBH_MmGGzI/AAAAAAAAbHE/HUYcYvkIwl0/s1600/AndroidImageViewSetImageFromURL2.png"));
// im.setImageResource(Uri.parse("https://www.amrita.edu/sites/default/files/%s", Newslist.get(position).getImage()));
// new DownloadImageTask(im).execute("https://www.amrita.edu/sites/default/files/" + Newslist.get(position).getImage());
return layout;
}
/*public void ofline(View view){
String filr_name="newfile";
FileOutputStream fileOutputStream = mContext.OpenfileOutput(filr_name,MODE_PRIVATE)
}
public void readmessage(View view){
}*/
#Override
public void destroyItem(ViewGroup collection, int position, Object view) {
collection.removeView((View) view);
}
#Override
public int getCount() {
return size;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public CharSequence getPageTitle(int position) {
ModelObject customPagerEnum = ModelObject.values()[position];
return mContext.getString(customPagerEnum.getTitleResId());
}
}
When device is offline you can import /read from a File or database which contains this json value . After getting internet update the database or file .
For file you must make or move the file in
Environment.getExternalStorageDirectory();
And for writing in a file follow the code
private void writeToFile(String data,Context context) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("test.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
And reading from external storage follow the following code
private String readFromFile(Context context) {
String ret = "";
try {
InputStream inputStream = context.openFileInput("test.txt");
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return ret;
}
I am developing an app where on some page user need to select one option from given 4-5 options currently I'm using spinner for this functionality now the question is, if user selects 3rd or 4th option(only single option selection permitted) select how do i insert that particular option in mysql php database.following is the code I'm using right now..
//MainActivity.java
public class MainActivity_D extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
//Declaring an Spinner
private Spinner spinner2, spinner1;
private String str_spinner1, str_spinner2, s_name, s_course;
//An ArrayList for Spinner Items
private ArrayList<String> students1;
private ArrayList<String> students2;
Button mBtnSave;
//JSON Array
private JSONArray result1, result2, result;
//TextViews to display details
private TextView textViewName1;
private TextView textViewName2;
private TextView textViewCourse;
private TextView textViewSession;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainactivity_d);
//Initializing the ArrayList
students1 = new ArrayList<String>();
students2 = new ArrayList<String>();
//Initializing Spinner
//Adding an Item Selected Listener to our Spinner
//As we have implemented the class Spinner.OnItemSelectedListener to this class iteself we are passing this to setOnItemSelectedListener
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner2 = (Spinner) findViewById(R.id.spinner2);
spinner1.setOnItemSelectedListener(this);
spinner2.setOnItemSelectedListener(this);
mBtnSave = (Button) findViewById(R.id.button2);
mBtnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
submitForm();
}
});
//Initializing TextViews
textViewName1 = (TextView) findViewById(R.id.textViewName1);
textViewName2 = (TextView) findViewById(R.id.textViewName2);
// textViewCourse = (TextView) findViewById(R.id.textViewCourse);
// textViewSession = (TextView) findViewById(R.id.textViewSession);
//This method will fetch the data from the URL
getData1();
getData2();
}
private void submitForm() {
// Submit your form here. your form is valid
//Toast.makeText(this, "Submitting form...", Toast.LENGTH_LONG).show();
// s_name = spinner1.getSelectedItem().toString();
// s_course = spinner2.getSelectedItem().toString();
Toast.makeText(this, "Signing up...", Toast.LENGTH_SHORT).show();
new InsertActivity(this).execute(s_name, s_course);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (parent.getId()){
case R.id.spinner1:
spinner1.setSelection(position);
s_name = (String) spinner1.getSelectedItem();
// getData1();
// showToast("Spinner1: position=" + position);
break;
case R.id.spinner2:
spinner2.setSelection(position);
s_course = (String) spinner2.getSelectedItem();
// getData2();
break;
}
/*if(spinner1.getId()==R.id.spinner1) {
textViewName1.setText(getName(position));
}
else if(spinner2.getId()==R.id.spinner2)
{
textViewName2.setText(getCourse(position));
}
switch (parent.getId()){
case R.id.spinner1:
// getData1();
// showToast("Spinner1: position=" + position);
break;
case R.id.spinner2:
// getData2();
break;
}*/
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
/* private String getName(int position){
String name="";
try {
//Getting object of given index
JSONObject json = result.getJSONObject(position);
//Fetching name from that object
name = json.getString(Config.TAG_NAME);
} catch (JSONException e) {
e.printStackTrace();
}
//Returning the name
return name;
}
private String getCourse(int position){
String course="";
try {
JSONObject json = result.getJSONObject(position);
course = json.getString(Config.TAG_COURSE);
} catch (JSONException e) {
e.printStackTrace();
}
return course;
}*/
private void getData1() {
//Creating a string request
StringRequest stringRequest1 = new StringRequest(Config.DATA_URL1,
new Response.Listener<String>() {
#Override
public void onResponse(String response1) {
JSONObject j1 = null;
try {
//Parsing the fetched Json String to JSON Object
j1 = new JSONObject(response1);
//Storing the Array of JSON String to our JSON Array
result1 = j1.getJSONArray(Config.JSON_ARRAY1);
//Calling method getStudents to get the students from the JSON Array
getStudents1(result1);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error1) {
}
});
//Creating a request queue
RequestQueue requestQueue1 = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue1.add(stringRequest1);
}
private void getStudents1(JSONArray j1) {
//Traversing through all the items in the json array
for (int i = 0; i < j1.length(); i++) {
try {
//Getting json object
JSONObject json1 = j1.getJSONObject(i);
//Adding the name of the student to array list
students1.add(json1.getString(Config.TAG_COURSE));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
spinner1.setAdapter(new ArrayAdapter<String>(MainActivity_D.this, android.R.layout.simple_spinner_dropdown_item, students1));
}
//Initializing TextViews
// textViewCourse = (TextView) findViewById(R.id.textViewCourse);
// textViewSession = (TextView) findViewById(R.id.textViewSession);
//This method will fetch the data from the URL
private void getData2() {
//Creating a string request
StringRequest stringRequest2 = new StringRequest(Config.DATA_URL2,
new Response.Listener<String>() {
#Override
public void onResponse(String response2) {
JSONObject j2 = null;
try {
//Parsing the fetched Json String to JSON Object
j2 = new JSONObject(response2);
//Storing the Array of JSON String to our JSON Array
result = j2.getJSONArray(Config.JSON_ARRAY);
//Calling method getStudents to get the students from the JSON Array
getStudents2(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error1) {
}
});
//Creating a request queue
RequestQueue requestQueue2 = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue2.add(stringRequest2);
}
private void getStudents2(JSONArray j2) {
//Traversing through all the items in the json array
for (int i = 0; i < j2.length(); i++) {
try {
//Getting json object
JSONObject json2 = j2.getJSONObject(i);
//Adding the name of the student to array list
students2.add(json2.getString(Config.TAG_USERNAME));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
spinner2.setAdapter(new ArrayAdapter<String>(MainActivity_D.this, android.R.layout.simple_spinner_dropdown_item, students2));
}
}
//InsertActivity.java
public class InsertActivity extends AsyncTask<String, Void, String> {
private Context context;
Boolean error, success;
public InsertActivity(Context context) {
this.context = context;
}
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... arg0) {
String s_name = arg0[0];
// String userName = arg0[1];
String s_course = arg0[1];
String link;
String data;
BufferedReader bufferedReader;
String result;
try {
data = "?s_name=" + URLEncoder.encode(s_name, "UTF-8");
// data += "&username=" + URLEncoder.encode(userName, "UTF-8");
data += "&s_course=" + URLEncoder.encode(s_course, "UTF-8");
link = "http://insert_s1.php" + data;
// link = "http://example.com/mangoair10/tryrr.php" + data;
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
result = bufferedReader.readLine();
return result;
} catch (Exception e) {
// return new String("Exception: " + e.getMessage());
// return null;
}
return null;
}
/* #Override
protected void onPostExecute(String result) {
String jsonStr = result;
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String query_result = jsonObj.getString("success");
String message_result = jsonObj.getString("message");
if (query_result.equalsIgnoreCase("1")) {
Toast.makeText(context,message_result , Toast.LENGTH_LONG).show();
} else if (query_result.equalsIgnoreCase("-1")) {
Toast.makeText(context, message_result, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}*/
#Override
protected void onPostExecute(String result) {
String jsonStr = result;
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String query_result = jsonObj.getString("query_result");
Log.e("TAG", String.valueOf(query_result));
// String message_result = jsonObj.getString("message");
/* if (query_result.equals("SUCCESS")) {
Toast.makeText(context, "Insert", Toast.LENGTH_LONG).show();
} else if(query_result.equals("FAILURE")){
Toast.makeText(context, "Unable to Insert", Toast.LENGTH_LONG).show();
}*/
} catch (JSONException e) {
e.printStackTrace();
}
}
}
//Config.java
public class Config {
//JSON URL
// public static final String DATA_URL = "http://example.com/jsonphp1.php";
public static final String DATA_URL1 = "http://example.com/jsonphp2.php";
public static final String DATA_URL2 = "http://example.com/jsonphp1.php";
//Tags used in the JSON String
public static final String TAG_USERNAME = "username";
public static final String TAG_NAME = "name";
public static final String TAG_COURSE = "course";
public static final String TAG_SESSION = "session";
//JSON array name
public static final String JSON_ARRAY = "result";
public static final String JSON_ARRAY1 = "result1";
public static final String JSON_ARRAY2 = "result2";
}
//this is my php file
<?php
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
$s_name=$_POST['s_name'];
$s_course=$_POST['s_course'];
Sid=$_GET['id'];
$query = "UPDATE `students` SET s_name = '$s_name', s_course= '$s_course' WHERE id='$id'";
$inserted = mysqli_query($con, $query);
// echo $inserted;
if($inserted) {
echo '{"query_result":"SUCCESS"}';
}
else{
echo '{"query_result":"FAILURE"}';
}
mysqli_close($con);
?>
The error is self explanatory. You are getting an Integer in your response which cannot be converted to a JSONObject. Log your response and check if it is a valid JSON.
In your asyntask onPostExecute method print response like this and post your response then error will be detected
#Override
protected void onPostExecute(String result) {
String jsonStr = result;
Log.e("TAG",jsonStr );
}
Here,I already fetched data from mysql db and this data shows into the spinner Now the problem is, I want to save spinner selected item into mysql database with different table, the item which i select from spinner it should save to database, how can i do this? By using php mysql i insert record into spinner and i want to update the records of register table with spinner selected item.Can i update the register table with spinner selected item values? please suggest me.
java file
public class MainActivity_d3 extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
//Declaring an Spinner
private Spinner spinner2, spinner1;
private String str_spinner1, str_spinner2, s_name, s_course;
//An ArrayList for Spinner Items
private ArrayList<String> students1;
private ArrayList<String> students2;
Button mBtnSave;
//JSON Array
private JSONArray result1, result2, result;
//TextViews to display details
private TextView textViewName1;
private TextView textViewName2;
private TextView textViewCourse;
private TextView textViewSession;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainactivity_d1);
//Initializing the ArrayList
students1 = new ArrayList<String>();
students2 = new ArrayList<String>();
//Initializing Spinner
//Adding an Item Selected Listener to our Spinner
//As we have implemented the class Spinner.OnItemSelectedListener to this class iteself we are passing this to setOnItemSelectedListener
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner2 = (Spinner) findViewById(R.id.spinner2);
spinner1.setOnItemSelectedListener(this);
spinner2.setOnItemSelectedListener(this);
mBtnSave = (Button) findViewById(R.id.button2);
mBtnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
submitForm();
}
});
//Initializing TextViews
textViewName1 = (TextView) findViewById(R.id.textViewName1);
textViewName2 = (TextView) findViewById(R.id.textViewName2);
// textViewCourse = (TextView) findViewById(R.id.textViewCourse);
// textViewSession = (TextView) findViewById(R.id.textViewSession);
//This method will fetch the data from the URL
getData1();
getData2();
}
private void submitForm() {
// Submit your form here. your form is valid
//Toast.makeText(this, "Submitting form...", Toast.LENGTH_LONG).show();
s_name = spinner1.getSelectedItem().toString();
s_course = spinner2.getSelectedItem().toString();
Toast.makeText(this, "Signing up...", Toast.LENGTH_SHORT).show();
new InsertActivity(this).execute(s_name, s_course);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
/*if(spinner1.getId()==R.id.spinner1) {
textViewName1.setText(getName(position));
}
else if(spinner2.getId()==R.id.spinner2)
{
textViewName2.setText(getCourse(position));
}
/* switch (view.getId()){
case R.id.spinner1:
getData1();
break;
case R.id.spinner2:
getData2();
break;
}*/
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
/* private String getName(int position){
String name="";
try {
//Getting object of given index
JSONObject json = result.getJSONObject(position);
//Fetching name from that object
name = json.getString(Config.TAG_NAME);
} catch (JSONException e) {
e.printStackTrace();
}
//Returning the name
return name;
}
private String getCourse(int position){
String course="";
try {
JSONObject json = result.getJSONObject(position);
course = json.getString(Config.TAG_COURSE);
} catch (JSONException e) {
e.printStackTrace();
}
return course;
}*/
private void getData1() {
//Creating a string request
StringRequest stringRequest1 = new StringRequest(Config.DATA_URL1,
new Response.Listener<String>() {
#Override
public void onResponse(String response1) {
JSONObject j1 = null;
try {
//Parsing the fetched Json String to JSON Object
j1 = new JSONObject(response1);
//Storing the Array of JSON String to our JSON Array
result1 = j1.getJSONArray(Config.JSON_ARRAY1);
//Calling method getStudents to get the students from the JSON Array
getStudents1(result1);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error1) {
}
});
//Creating a request queue
RequestQueue requestQueue1 = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue1.add(stringRequest1);
}
private void getStudents1(JSONArray j1) {
//Traversing through all the items in the json array
for (int i = 0; i < j1.length(); i++) {
try {
//Getting json object
JSONObject json1 = j1.getJSONObject(i);
//Adding the name of the student to array list
students1.add(json1.getString(Config.TAG_COURSE));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
spinner1.setAdapter(new ArrayAdapter<String>(MainActivity_d3.this, android.R.layout.simple_spinner_dropdown_item, students1));
}
//Initializing TextViews
// textViewCourse = (TextView) findViewById(R.id.textViewCourse);
// textViewSession = (TextView) findViewById(R.id.textViewSession);
//This method will fetch the data from the URL
private void getData2() {
//Creating a string request
StringRequest stringRequest2 = new StringRequest(Config.DATA_URL2,
new Response.Listener<String>() {
#Override
public void onResponse(String response2) {
JSONObject j2 = null;
try {
//Parsing the fetched Json String to JSON Object
j2 = new JSONObject(response2);
//Storing the Array of JSON String to our JSON Array
result = j2.getJSONArray(Config.JSON_ARRAY);
//Calling method getStudents to get the students from the JSON Array
getStudents2(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error1) {
}
});
//Creating a request queue
RequestQueue requestQueue2 = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue2.add(stringRequest2);
}
private void getStudents2(JSONArray j2) {
//Traversing through all the items in the json array
for (int i = 0; i < j2.length(); i++) {
try {
//Getting json object
JSONObject json2 = j2.getJSONObject(i);
//Adding the name of the student to array list
students2.add(json2.getString(Config.TAG_USERNAME));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
spinner2.setAdapter(new ArrayAdapter<String>(MainActivity_d3.this, android.R.layout.simple_spinner_dropdown_item, students2));
}
}
//InsertActivity
public class InsertActivity extends AsyncTask<String, Void, String> {
private Context context;
Boolean error, success;
public InsertActivity(Context context) {
this.context = context;
}
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... arg0) {
String s_name = arg0[0];
// String userName = arg0[1];
String s_course = arg0[1];
String link;
String data;
BufferedReader bufferedReader;
String result;
try {
data = "?s_name=" + URLEncoder.encode(s_name, "UTF-8");
// data += "&username=" + URLEncoder.encode(userName, "UTF-8");
data += "&s_course=" + URLEncoder.encode(s_course, "UTF-8");
link = "http://mangoair.in/Spinner/insert_s1.php" + data;
// link = "http://hostogen.com/mangoair10/tryrr.php" + data;
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
result = bufferedReader.readLine();
return result;
} catch (Exception e) {
// return new String("Exception: " + e.getMessage());
// return null;
}
return null;
}
/* #Override
protected void onPostExecute(String result) {
String jsonStr = result;
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String query_result = jsonObj.getString("success");
String message_result = jsonObj.getString("message");
if (query_result.equalsIgnoreCase("1")) {
Toast.makeText(context,message_result , Toast.LENGTH_LONG).show();
} else if (query_result.equalsIgnoreCase("-1")) {
Toast.makeText(context, message_result, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}*/
#Override
protected void onPostExecute(String result) {
String jsonStr = result;
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String query_result = jsonObj.getString("query_result");
if (query_result.equalsIgnoreCase("SUCCESS")) {
Toast.makeText(context, "Data inserted successfully. Signup successfully.", Toast.LENGTH_LONG).show();
} else if (query_result.equalsIgnoreCase("FAILURE")) {
Toast.makeText(context, "Data could not be inserted, fill all records.", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Get the value from the spinner as a string and just pass this string like a normal string
I want to show a ProgressDialog while waiting for server's response.
My class JogarActivity does the following (My app is a quiz game):
1- Initialize variables
2- Verify if it is or not the first question (primeiraPergunta)
2.1- If it's the first question, calls UserFunctions.getJogar(). This function build an list with parameters and send it to a JSONParser class. JSONParser makes the http request and returns a JSONArray with data
2.2- If it isn't the first question, just retrieve the actual question from intent extras.
3- Try to parse JSONArray to string. If the user had already answered all questions in the actual category, this will return an Exception (JSONArray will be null), so it can show a dialog asking user to select another category.
4- Puts all data (question and answer options) on screen and wait for user's interaction.
5- When user select an answer, it calls UserFunctions.gerResposta(). This time, it will return a status message (correct, wrong, error, etc) after updating the database (ponctuation, answered questions etc). It will also retrieve the next question.
6- Show a dialog with info about the question and an OK button that, when pressed, restarts the activity. The next question is passed as intent.putExtra(), and primeiraPergunta (first question?) is setted to false.
*UserFunctions and JSONParser are not activities, so I can't use ProgressDialog inside them, as long as I can't retrieve application's context.
*JSONParser is used by other classes, so I prefer not to changing it
*I'm looking for another solution than rewriting everithing in JogarActivity (that will make necessary to change other classes too).
first below i've pasted JogarActivity without changes. Then, I've tried to add an AsyncTask to show the ProgressDialog, but it just doesn't appears on screen (AsyncTask.get() is used to make JogarActivity wait for results from asynctask). Finnaly, i've pasted another class (RegisterActivity) where the AsyncTask works just fine.
I guess AsyncTask is probably not the best approach, but I just want to make it works as soon as possible. This is not my code (except for RegisterActivity). After the app works i'll optimize it :)
==========JogarActivity.java====================
public class JogarActivity extends Activity {
private static final String TAG_RESPOSTA = "resposta";
private static final String TAG_ID = "idt";
private static final String TAG_PRIMEIRAPERGUNTA = "primeiraPergunta";
private static final String TAG_JSON = "json";
private Integer idPergunta;
private String pergunta;
private String respostaRecebe; //Texto da resposta que o usuário escolheu
private String respostaConfere;
private String resposta;
private String idCategoria;
private String respostaCorreta;
private String[] arrayRespostas = new String[5];
private boolean primeiraPergunta;
private JSONArray json;
private JSONArray jsonResposta;
String idUser;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.jogar_layout);
Intent in = getIntent();
String url = this.getString(R.string.urlSite);
ArrayList<HashMap<String, String>> respostaList = new ArrayList<HashMap<String, String>>();
String idt = in.getStringExtra(TAG_ID);
primeiraPergunta = in.getBooleanExtra(TAG_PRIMEIRAPERGUNTA, true);
TextView insertPergunta = (TextView) findViewById(R.id.insertPergunta);
ListView insertRespostas = (ListView) findViewById(R.id.listResposta);
SharedPreferences settings = getSharedPreferences("PREFS_LOGIN", MODE_PRIVATE);
Integer idUsuario = settings.getInt("idUsuario", 0);
idUser = idUsuario.toString();
if (primeiraPergunta){
UserFunctions userFunction = new UserFunctions();
json = userFunction.getJogar(idt, idUser);
}else{
try {
json = new JSONArray(in.getStringExtra(TAG_JSON));
json = json.getJSONArray(2);
} catch (JSONException e) {
e.printStackTrace();
}
}
try{
#SuppressWarnings("unused")
String s = json.toString(); // Se o usuário já respondeu todas as perguntas da categoria, retorna uma Exception
try {
idPergunta = json.getInt(0);
pergunta = json.getString(1);
for (int i=2; i<7 ; i++){
resposta = json.getString(i);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_RESPOSTA, resposta);
respostaList.add(map);
arrayRespostas[i-2] = resposta;
}
respostaCorreta = json.getString(7);
respostaConfere = arrayRespostas[Integer.parseInt(respostaCorreta)-1];
idCategoria = json.getString(11);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
insertPergunta.setText(pergunta);
ListAdapter adapter = new SimpleAdapter(this, respostaList,
R.layout.resposta_data,
new String[] { TAG_RESPOSTA }, new int[] {
R.id.insertResposta });
insertRespostas.setAdapter(adapter);
// selecting single ListView item
ListView lv = insertRespostas;
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
Integer pos = position + 1;
String respostaEscolhida = pos.toString();
String pergunta = idPergunta.toString();
UserFunctions userFunction = new UserFunctions();
final JSONArray jsonResposta = userFunction.getResposta(pergunta, idUser , respostaEscolhida, idCategoria);
respostaRecebe = arrayRespostas[position];
String mensagem = "";
try {
mensagem = jsonResposta.getString(1);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
final String jrString = jsonResposta.toString();
AlertDialog alertDialog = new AlertDialog.Builder(
JogarActivity.this).create();
if (respostaCorreta.equals(pos.toString())){
alertDialog.setTitle("PARABÉNS");
alertDialog.setMessage("Resposta correta: "+respostaRecebe+"\n\n"+mensagem);
}
else{
alertDialog.setTitle("VOCÊ ERROU");
alertDialog.setMessage("Sua resposta: "+respostaRecebe+"\n\nResposta correta: "+respostaConfere+"\n\n"+mensagem);
}
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(getApplicationContext(),JogarActivity.class);
//in.putExtra(TAG_NAME, name);
i.putExtra(TAG_ID, idCategoria);
i.putExtra(TAG_PRIMEIRAPERGUNTA, false);
i.putExtra(TAG_JSON, jrString);
startActivity(i);
finish();
}
});
alertDialog.show();
}
});
}catch (Exception e){
AlertDialog sem_perguntas = new AlertDialog.Builder(
JogarActivity.this).create();
sem_perguntas.setTitle("PARABÉNS");
sem_perguntas.setMessage("Você já respondeu todas as perguntas desta categoria!");
sem_perguntas.setButton("VOLTAR", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(getApplicationContext(),CategoriasJogarActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(i);
finish();
}
});
sem_perguntas.show();
//finish();
}
//finish();
}
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.layout.menu_jogar, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.menu_pularPergunta:
Intent i = new Intent(getApplicationContext(),JogarActivity.class);
startActivity(i);
finish();
Toast.makeText(JogarActivity.this, "Pergunta Pulada", Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
}
==============JogarActivity with AsyncTask (ProgressDialog doesn't appears)=============
public class JogarActivity extends Activity {
private static final String TAG_RESPOSTA = "resposta";
private static final String TAG_ID = "idt";
private static final String TAG_PRIMEIRAPERGUNTA = "primeiraPergunta";
private static final String TAG_JSON = "json";
private Integer idPergunta;
private String pergunta;
private String respostaRecebe; //Texto da resposta que o usuário escolheu
private String respostaConfere;
private String resposta;
private String idCategoria;
private String respostaCorreta;
private String[] arrayRespostas = new String[5];
private boolean primeiraPergunta;
private JSONArray json;
private JSONArray jsonResposta;
ProgressDialog pDialog;
Context ctx = this;
String idUser;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.jogar_layout);
Intent in = getIntent();
String url = this.getString(R.string.urlSite);
ArrayList<HashMap<String, String>> respostaList = new ArrayList<HashMap<String, String>>();
String idt = in.getStringExtra(TAG_ID);
primeiraPergunta = in.getBooleanExtra(TAG_PRIMEIRAPERGUNTA, true);
TextView insertPergunta = (TextView) findViewById(R.id.insertPergunta);
ListView insertRespostas = (ListView) findViewById(R.id.listResposta);
SharedPreferences settings = getSharedPreferences("PREFS_LOGIN", MODE_PRIVATE);
Integer idUsuario = settings.getInt("idUsuario", 0);
idUser = idUsuario.toString();
if (primeiraPergunta){
//UserFunctions userFunction = new UserFunctions();
//json = userFunction.getJogar(idt, idUser);
AsyncTask jogar = new Jogar().execute("url", "http://www.qranio.com/mobile/perguntas.php", "categoria", idt, "idUsuario", idUser);
try {
json = (JSONArray) jogar.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}else{
try {
json = new JSONArray(in.getStringExtra(TAG_JSON));
json = json.getJSONArray(2);
} catch (JSONException e) {
e.printStackTrace();
}
}
try{
#SuppressWarnings("unused")
String s = json.toString(); // Se o usuário já respondeu todas as perguntas da categoria, retorna uma Exception
try {
idPergunta = json.getInt(0);
pergunta = json.getString(1);
for (int i=2; i<7 ; i++){
resposta = json.getString(i);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_RESPOSTA, resposta);
respostaList.add(map);
arrayRespostas[i-2] = resposta;
}
respostaCorreta = json.getString(7);
respostaConfere = arrayRespostas[Integer.parseInt(respostaCorreta)-1];
idCategoria = json.getString(11);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
insertPergunta.setText(pergunta);
ListAdapter adapter = new SimpleAdapter(this, respostaList,
R.layout.resposta_data,
new String[] { TAG_RESPOSTA }, new int[] {
R.id.insertResposta });
insertRespostas.setAdapter(adapter);
// selecting single ListView item
ListView lv = insertRespostas;
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
Integer pos = position + 1;
String respostaEscolhida = pos.toString();
String pergunta = idPergunta.toString();
//UserFunctions userFunction = new UserFunctions();
//final JSONArray jsonResposta = userFunction.getResposta(pergunta, idUser , respostaEscolhida, idCategoria);
AsyncTask jogar = new Jogar().execute("url", "http://www.qranio.com/mobile/resposta.php", "id_pergunta", pergunta, "id_usuario", idUser, "resposta", respostaEscolhida, "categoria", idCategoria);
try {
jsonResposta = (JSONArray) jogar.get();
} catch (InterruptedException e1) {
e1.printStackTrace();
} catch (ExecutionException e1) {
e1.printStackTrace();
}
respostaRecebe = arrayRespostas[position];
String mensagem = "";
try {
mensagem = jsonResposta.getString(1);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
final String jrString = jsonResposta.toString();
AlertDialog alertDialog = new AlertDialog.Builder(
JogarActivity.this).create();
if (respostaCorreta.equals(pos.toString())){
alertDialog.setTitle("PARABÉNS");
alertDialog.setMessage("Resposta correta: "+respostaRecebe+"\n\n"+mensagem);
}
else{
alertDialog.setTitle("VOCÊ ERROU");
alertDialog.setMessage("Sua resposta: "+respostaRecebe+"\n\nResposta correta: "+respostaConfere+"\n\n"+mensagem);
}
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(getApplicationContext(),JogarActivity.class);
//in.putExtra(TAG_NAME, name);
i.putExtra(TAG_ID, idCategoria);
i.putExtra(TAG_PRIMEIRAPERGUNTA, false);
i.putExtra(TAG_JSON, jrString);
startActivity(i);
finish();
}
});
alertDialog.show();
}
});
}catch (Exception e){
AlertDialog sem_perguntas = new AlertDialog.Builder(
JogarActivity.this).create();
sem_perguntas.setTitle("PARABÉNS");
sem_perguntas.setMessage("Você já respondeu todas as perguntas desta categoria!");
sem_perguntas.setButton("VOLTAR", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(getApplicationContext(),CategoriasJogarActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(i);
finish();
}
});
sem_perguntas.show();
//finish();
}
//finish();
}
/*public void colocaResposta (int i, JSONArray json, ArrayList respostaList) throws JSONException{
resposta = json.getString(i);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_RESPOSTA, resposta);
respostaList.add(map);
}*/
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.layout.menu_jogar, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.menu_pularPergunta:
Intent i = new Intent(getApplicationContext(),JogarActivity.class);
startActivity(i);
finish();
Toast.makeText(JogarActivity.this, "Pergunta Pulada", Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
class Jogar extends AsyncTask<String, Void, JSONArray>{
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ctx);
pDialog.setMessage("Aguarde...");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected JSONArray doInBackground(String... values) {
String url = values[1];
int count = values.length;
List<NameValuePair> params = new ArrayList<NameValuePair>();
for (int i=2; i<count; i++){
params.add(new BasicNameValuePair(values[i], values[i+1]));
i++;
}
JSONParser jsonParser = new JSONParser();
JSONArray json = jsonParser.getJSONFromUrl(url, params);
return json;
}
protected void onPostExecute(JSONArray result) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
=================RegisterActivity (Works fine)======================
public class RegisterActivity extends Activity{
EditText reg_fullname;
EditText reg_email;
EditText reg_login;
EditText reg_password;
EditText reg_password2;
Spinner reg_country;
Spinner reg_genre;
EditText reg_birthday;
EditText reg_promocode;
Button btnRegister;
Context ctx = this;
ProgressDialog pDialog;
JSONArray json;
String status;
String msg;
String fullname;
String email;
String login;
String password;
String password2;
String country;
String genre;
String birthday;
String promocode;
boolean finishActivity = false;
/**
* #see android.app.Activity#onCreate(Bundle)
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
TextView loginScreen = (TextView) findViewById(R.id.link_to_login);
loginScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// Closing registration screen
// Switching to Login Screen/closing register screen
finish();
}
});
reg_fullname = (EditText) findViewById(R.id.reg_fullname);
reg_email = (EditText) findViewById(R.id.reg_email);
reg_login = (EditText) findViewById(R.id.reg_login);
reg_password = (EditText) findViewById(R.id.reg_password);
reg_password2 = (EditText) findViewById(R.id.reg_password2); //confirmação de senha
reg_country = (Spinner) findViewById(R.id.reg_country);
reg_genre = (Spinner) findViewById(R.id.reg_genre);
reg_birthday = (EditText) findViewById(R.id.reg_birthday);
reg_promocode = (EditText) findViewById(R.id.reg_promocode);
btnRegister = (Button) findViewById(R.id.btnRegister);
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fullname = reg_fullname.getText().toString();
email = reg_email.getText().toString();
login = reg_login.getText().toString();
password = reg_password.getText().toString();
password2 = reg_password2.getText().toString();
country = reg_country.getSelectedItem().toString();
genre = reg_genre.getSelectedItem().toString();
birthday = reg_birthday.getText().toString();
promocode = reg_promocode.getText().toString();
boolean validation = true;
String message = "Campo de preencimento obrigatório";
if(fullname.equalsIgnoreCase("")){
reg_fullname.setError(message);
validation = false;
}
if(email.equalsIgnoreCase("")){
reg_email.setError(message);
validation = false;
}
if(!email.matches(".*#.*")){
reg_email.setError("O endereço de email não é válido");
validation = false;
}
if(login.equalsIgnoreCase("")){
reg_login.setError(message);
validation = false;
}
if(password.equalsIgnoreCase("")){
reg_password.setError(message);
validation = false;
}
if(password2.equalsIgnoreCase("")){
reg_password2.setError(message);
validation = false;
}
if(!password.equals(password2)){
reg_password2.setError("A confirmação de senha não confere");
validation = false;
}
if(birthday.equalsIgnoreCase("")){
reg_birthday.setError(message);
validation = false;
}
SimpleDateFormat bd = new SimpleDateFormat("dd/MM/yyyy");
if(bd.parse(birthday, new ParsePosition(0)) == null){
reg_birthday.setError("Esta data não é válida! Preencha novamente, usando o formato dd/mm/aaaa");
validation = false;
}
if(validation){
new Register().execute();
}
}
});
}
class Register extends AsyncTask<Void, Void, JSONArray>{
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ctx);
pDialog.setMessage("Aguarde...");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected JSONArray doInBackground(Void... params) {
UserFunctions userFunction = new UserFunctions();
json = userFunction.newUser(fullname, email, login, password, country, genre, birthday, promocode);
return json;
}
protected void onPostExecute(JSONArray result) {
// dismiss the dialog once done
pDialog.dismiss();
final AlertDialog alertDialog = new AlertDialog.Builder(
RegisterActivity.this).create();
try {
status = json.getString(0);
msg = json.getString(1);
Log.d("Status", status);
} catch (JSONException e) {
Log.e("RegisterActiviry", "Error converting result " + e.toString());
e.printStackTrace();
status = null;
}
if (status.equalsIgnoreCase("erro")){
alertDialog.setTitle("Erro");
alertDialog.setMessage(msg);
}else if (status.equalsIgnoreCase("sucesso")){
alertDialog.setTitle("Sucesso!");
alertDialog.setMessage(msg);
finishActivity = true;
}else{
alertDialog.setTitle("Erro");
alertDialog.setMessage("Não foi possível realizar seu cadastro, tente novamente mais tarde.");
}
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if(finishActivity){
finish();
}else{
alertDialog.dismiss();
}
}
});
alertDialog.show();
}
}
}
put you dialog like below I hope it will work.
runOnUiThread(new Runnable() {
public void run() {
//Your dailog
}
});