I have an issue with my alertdialog - android

I created two activities: the first one contains details of a job offer, and the next one is to postulate to this job. after applying for the job, an alertdialog appears to confirm the success of the operation. However, this alertdialog appears in the view of the job details without values !
How can I manage this??
This is activity 1:
private static final String MY_PREFERENCES = "mespreferences";
TextView txt;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detail_offre);
ToggleButton precedent = (ToggleButton)findViewById(R.id.btn_preced);
precedent.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent preced = new Intent(DetailsOffre.this, Offres.class);
startActivity(preced);
}
});
Button postuler = (Button)findViewById(R.id.postuler);
postuler.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
TextView id_offre = (TextView) findViewById(R.id.tv_ID_Off1);
SharedPreferences settings = getSharedPreferences(MY_PREFERENCES, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("idoffre", id_offre.getText().toString());
editor.commit();
Intent intent_postul = new Intent(DetailsOffre.this, Candidature.class);
startActivity(intent_postul);
}
});
Button enregistrer = (Button)findViewById(R.id.enregistrer);
enregistrer.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
// TODO Auto-generated method stub
TextView id_offre = (TextView) findViewById(R.id.tv_ID_Off1);
String idOf = id_offre.getText().toString();
Intent intent_enregist = new Intent(DetailsOffre.this, EnregistrerOffre.class);
intent_enregist.putExtra("idoffre",idOf );
startActivity(intent_enregist);
}
});
LinearLayout rootLayout = new LinearLayout(getApplicationContext());
txt = new TextView(getApplicationContext());
rootLayout.addView(txt);
txt.setText("Connexion...");
txt.setText(getServerData(URL2));
}
public static final String URL2 = "http://10.0.2.2/mesRequetes/detail_offr.php";
private String getServerData(String returnString) {
InputStream is = null;
String result = null;
Intent intent3 = getIntent();
String id = intent3.getExtras().getString("idoffre");
ArrayList<NameValuePair> postID = new ArrayList<NameValuePair>();
postID.add(new BasicNameValuePair("idoffre", id));
// Envoie de la commande http
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL2);
httppost.setEntity(new UrlEncodedFormEntity(postID));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection " + e.toString());
}
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result " + e.toString());
}
try{
JSONArray jArray = new JSONArray(result);
JSONObject detail=null;
for(int i=0;i<jArray.length();i++){
detail = jArray.getJSONObject(i);
TextView numoffre = (TextView) findViewById(R.id.tv_ID_Off1);
numoffre.setText(detail.getString("idoffre"));
TextView nom_societe = (TextView) findViewById(R.id.tv_societe1);
nom_societe.setText(detail.getString("first_name"));
TextView poste = (TextView) findViewById(R.id.TV_post1);
poste.setText(detail.getString("poste"));
TextView ville = (TextView) findViewById(R.id.tv_vill);
ville.setText(detail.getString("ville"));
TextView details = (TextView) findViewById(R.id.tv_detail);
details.setText(detail.getString("details"));
TextView d_crea = (TextView) findViewById(R.id.tv_datecrea);
d_crea.setText(format_d(detail.getString("created_at")));
TextView idste = (TextView) findViewById(R.id.TV_idsociete1);
idste.setText(detail.getString("idsoc"));
SharedPreferences settings = getSharedPreferences(MY_PREFERENCES, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("idsoc", idste.getText().toString());
editor.commit();
Log.i("log_tag","Numero de l'offre:"+detail.getInt("idoffre")+
"poste proposé:"+detail.getString("poste")+
"ville:"+detail.getString("ville")+
"details:"+detail.getString("details")+
"date de creation:"+detail.getString("created_at")+
"identifiant de la société:"+detail.getString("idsoc")+
"nom de la société:"+detail.getString("first_name")
);
// Résultats de la requête
returnString += "" + jArray.getJSONObject(i);
};
}catch(JSONException e){
Log.e("log_tag", "Error parsing data " + e.toString());
}
return returnString;
}
public static StringBuilder format_d(final String s) {
String aaaa = s.substring(0, 4);
String mm = s.substring(5, 7);
String dd = s.substring(8, 10);
String heure = s.substring (11);
return new StringBuilder(dd)
.append("/")
.append(mm)
.append("/")
.append(aaaa)
.append(" à ")
.append(heure);
}
Activity2:
private static final String MY_PREFERENCES = "mespreferences";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detail_offre);
SharedPreferences sharedPreferences = getSharedPreferences(MY_PREFERENCES, 0);
String userId = sharedPreferences.getString("id", "");
String idoffr = sharedPreferences.getString("idoffre", "");
Intent intent_postul = getIntent();
ArrayList<NameValuePair> postCandidature= new ArrayList<NameValuePair>();
postCandidature.add(new BasicNameValuePair("idoffre", idoffr));
postCandidature.add(new BasicNameValuePair("id", userId));
this.sendData(postCandidature);
}
private void sendData(ArrayList<NameValuePair> postCandidature) {
// TODO Auto-generated method stub
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/mesRequetes/candidature.php");
httppost.setEntity(new UrlEncodedFormEntity(postCandidature));
HttpResponse response = httpclient.execute(httppost);
Log.i("postData", response.getStatusLine().toString());
AlertDialog.Builder cand = new AlertDialog.Builder(Candidature.this);
cand.setIcon(R.drawable.succes);
cand.setTitle("Succès");
cand.setMessage("Votre candidature a bien été transmise");
cand.setPositiveButton("OK", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Intent offr = new Intent (Candidature.this, Offres.class);
startActivity(offr);
}});
cand.show();
}catch(Exception e){
Log.e("log_tag", "Error in http connection " + e.toString());
}
}

Use the following for Alert Dialog. Give more details to understand your requirements.
public void Alert(String text, String title)
{
AlertDialog dialog=new AlertDialog.Builder(context).create();
dialog.setTitle(title);
dialog.setMessage(text);
if(!title.equals("") && !text.equals(""))
{
dialog.setButton("OK",
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int whichButton)
{
//
}
});
dialog.setButton2("Cancel",
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int whichButton)
{
//
}
});
}
dialog.show();
}

Related

How to update particular item in listview while on backpress from detail view page?

How to update particular item in list view while on back press from detail view page?
I'm having custom listview displaying items with like and dislike button, if i click the particular item it will navigate to detail page, in detail page user made any changes it show reflect on listview when user onbackpress in detail page. can anyone give me solution. i tried many method,but am not able to find solution.here is my code
Latest_Jokes.java
public class Latest_Jokes extends Fragment {
public Latest_Jokes() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
this.inflatedView = inflater.inflate(R.layout.latest_jokes, container, false);
// error_message = (RelativeLayout) inflatedView.findViewById(R.id.error_message);
pref = getActivity().getSharedPreferences("MyPref", 0);
editor = pref.edit();
width = getActivity().getResources().getDisplayMetrics().widthPixels;
extend = (ImageView) inflatedView.findViewById(R.id.extend);
listview = (ListView) inflatedView.findViewById(R.id.list_jokes);
userId = pref.getString("userId", null);
nsfwcode = pref.getString("nswKey", null);
Token = pref.getString("Token", null);
new LatestTask().execute(nsfwcode, userId);
return inflatedView;
}
private class LatestTask extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
InputStream inputStream = null;
String result = "";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Global_Url.jokes_url);
try {
userId = pref.getString("userId", null);
nsfwcode = pref.getString("nswKey", null);
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(3);
nameValuePair.add(new BasicNameValuePair("page", String.valueOf(current_page)));
nameValuePair.add(new BasicNameValuePair("uid", userId));
nameValuePair.add(new BasicNameValuePair("nsfw", nsfwcode));
nameValuePair.add(new BasicNameValuePair("token", Token));
Log.e("userId", userId + nsfwcode);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpclient.execute(httppost);
inputStream = response.getEntity().getContent();
if (inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
}
return result;
}
private String convertInputStreamToString(InputStream inputStream)
throws IOException {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream));
String line = "";
String result = "";
while ((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
#Override
protected void onPostExecute(String result) {
jsonStr = result;
if (jsonStr != null) {
JSONObject jsono = null;
try {
jsono = new JSONObject(jsonStr);
String error_status = jsono.getString("status");
Log.e("jsono", String.valueOf(jsono));
if (error_status.equals("0")) {
listview.setVisibility(View.GONE);
// error_message.setVisibility(View.VISIBLE);
} else if (error_status.equals("403")) {
FacebookSdk.sdkInitialize(getActivity());
LoginManager.getInstance().logOut();
editor.clear();
editor.commit();
Intent edit_page = new Intent(getContext(), Login.class);
startActivity(edit_page);
} else {
jarray = jsono.getJSONArray("data");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
jok_id.add(object.getString("jok_id"));
jok_desc.add(object.getString("jok_desc"));
jok_img.add(object.getString("jok_img"));
jok_is_active.add(object.getString("jok_is_active"));
jok_nsfw.add(object.getString("jok_nsfw"));
jok_total_comments.add(object.getString("jok_total_comments"));
jok_total_flags.add(object.getString("jok_total_flags"));
jok_total_shares.add(object.getString("jok_total_shares"));
jok_created_on.add(object.getString("jok_created_on"));
jok_modified_on.add(object.getString("jok_modified_on"));
userName.add(object.getString("jok_username"));
jokeLike.add(object.getString("likeStatus"));
jok_userimg.add(object.getString("jok_userimg"));
likeCount.add(object.getString("likeCount"));
dislikeCount.add(object.getString("dislikeCount"));
popularJoke.add(object.getString("jok_is_popular"));
languagename.add(object.getString("language"));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
listview.setAdapter(new CustomBaseAdapter(getActivity(), userName, jokeLike, jok_id, jok_desc, jok_img, jok_is_active, jok_nsfw,
jok_total_comments, jok_total_flags, jok_total_shares, jok_created_on
, jok_modified_on, jok_userimg, likeCount, dislikeCount, popularJoke, languagename));
}}}
DetailedViewJokes.java
public class DetailedViewJokes extends Activity {
private ProgressDialog pDialog;
Dialog dialog;
final Context context = this;
String encoded;
JSONArray contacts = null;
String option,jokeingid,Token;
int post;
String path;
private static final String TAG_DATA = "data";
private static final String TAG_COMMENTS = "comments";
private static final String TAG_STATUS = "status";
private static final String TAG_NAME = "username";
private static final String TAG_IMAGE = "image";
ArrayList<HashMap<String, String>> contactList;
String detailview_name,detailview_smile,detailview_frown,detailview_comments,detailview_share,
detailview_jokeimage,detailview_profile,detailview_desc,detailview_time,detailview_jokeid,userId, likeStatus,popularstatus,user_type_id
, commentClick,lang,like_response;
public static String jokeindex = null;
TextView detail_language,title,frowns,comments,detail_name,detail_smile_count,detail_frown_count,detail_comment_count,detail_share_count,detail_description,detail_time,comment_button,comment_hide;
ImageView detail_joke_image,detail_profile_image;
LinearLayout share,comment_icon,comment_layout,detail_flag_icon,mLinearListView,layout_bottom,layout2;
EditText commit_et;
CheckBox detail_mark_popular;
private SharedPreferences.Editor editor;
private SharedPreferences pref;
Intent i;
String comment,userLikeString,userDislikeString;
File file;
Bitmap bmp;
ScrollView scroll;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.details_view);
pref = getSharedPreferences("MyPref", 0);
editor = pref.edit();
userId = pref.getString("userId", null);
Token = pref.getString("Token",null);
user_type_id = pref.getString("typeId", null);
Toast.makeText(getApplicationContext(), CustomBaseAdapter.jokeLike+"", Toast.LENGTH_SHORT).show();
new AsyncHttpTask().execute();
//ListView lv = getListView();
i = getIntent();
Bundle extras = i.getExtras();
contactList = new ArrayList<HashMap<String, String>>();
detail_name = (TextView) findViewById(R.id.detail_name);
detail_smile_count = (TextView) findViewById(R.id.detail_smile_count);
detail_frown_count = (TextView) findViewById(R.id.detail_frown_count);
detail_comment_count = (TextView) findViewById(R.id.detail_comment_count);
detail_share_count = (TextView) findViewById(R.id.detail_share_count);
detail_time = (TextView) findViewById(R.id.detail_time);
detail_description = (TextView) findViewById(R.id.detail_descc);
comment_button = (TextView) findViewById(R.id.comment_button);
comment_hide = (TextView) findViewById(R.id.comment_hide);
scroll = (ScrollView) findViewById(R.id.detail_scroll);
detail_language = (TextView) findViewById(R.id.detail_language);
layout_bottom = (LinearLayout) findViewById(R.id.layout_bottom);
detail_joke_image = (ImageView) findViewById(R.id.detail_joke_image);
detail_profile_image = (ImageView) findViewById(R.id.detail_user_profile);
detail_mark_popular = (CheckBox) findViewById(R.id.detail_mark_popular);
final ImageView detail_up = (ImageView) findViewById(R.id.detail_up);
final ImageView detail_downe = (ImageView) findViewById(R.id.detail_down);
mLinearListView = (LinearLayout) findViewById(R.id.commentlist);
layout2 = (LinearLayout)findViewById(R.id.layout2);
commit_et = (EditText) findViewById(R.id.comment_tv);
title = (TextView) findViewById(R.id.title);
frowns = (TextView) findViewById(R.id.frowns);
comments = (TextView) findViewById(R.id.comments);
comment_icon = (LinearLayout) findViewById(R.id.detail_comment_icon);
comment_layout = (LinearLayout) findViewById(R.id.comment_layout);
detail_flag_icon = (LinearLayout) findViewById(R.id.detail_flag_icon);
if(likeStatus.equals("1")){
detail_up.setImageResource(R.drawable.upvotes);
}else if(likeStatus.equals("2")) {
detail_downe.setImageResource(R.drawable.downvotes);
}
detail_up.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
detail_up.setImageResource(R.drawable.upvotes);
detail_downe.setImageResource(R.drawable.downvotes_gray);
like_response ="You Upvoted";
userLikeString = pref.getString("userLike", null); // getting String
userDislikeString = pref.getString("userDislike", null);
if(likeStatus.equals("1")){
}else if(likeStatus.equals("2")){
detail_smile_count.setText(String.valueOf(Integer.parseInt(detailview_smile) + 1));
detail_frown_count.setText(String.valueOf(Integer.parseInt(detailview_frown) - 1));
detailview_smile = detail_smile_count.getText().toString();
detailview_frown = detail_frown_count.getText().toString();
editor.putString("userLike", String.valueOf(Integer.parseInt(userLikeString) + 1));
editor.putString("userDislike", String.valueOf(Integer.parseInt(userDislikeString) - 1));
editor.commit();
userLikeString = pref.getString("userLike", null); // getting String
userDislikeString = pref.getString("userDislike", null);
TabMenu.userLikeTextView.setText(userLikeString);
TabMenu.userDislikeTextView.setText(userDislikeString);
}else {
detail_smile_count.setText(String.valueOf(Integer.parseInt(detailview_smile) + 1));
detailview_smile = detail_smile_count.getText().toString();
editor.putString("userLike", String.valueOf(Integer.parseInt(userLikeString) + 1));
editor.commit();
userLikeString = pref.getString("userLike", null); // getting String
TabMenu.userLikeTextView.setText(userLikeString);
}
likeStatus = "1";
new LikeTask().execute(likeStatus);
}
});
detail_downe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
detail_up.setImageResource(R.drawable.upvotes_gray);
detail_downe.setImageResource(R.drawable.downvotes);
like_response ="You Downvoted";
userLikeString = pref.getString("userLike", null); // getting String
userDislikeString = pref.getString("userDislike", null);
if(likeStatus.equals("1")){
detail_smile_count.setText(String.valueOf(Integer.parseInt(detailview_smile) - 1));
detail_frown_count.setText(String.valueOf(Integer.parseInt(detailview_frown) + 1));
detailview_smile = detail_smile_count.getText().toString();
detailview_frown = detail_frown_count.getText().toString();
editor.putString("userLike", String.valueOf(Integer.parseInt(userLikeString) - 1));
editor.putString("userDislike", String.valueOf(Integer.parseInt(userDislikeString) + 1));
editor.commit();
userLikeString = pref.getString("userLike", null); // getting String
userDislikeString = pref.getString("userDislike", null);
TabMenu.userLikeTextView.setText(userLikeString);
TabMenu.userDislikeTextView.setText(userDislikeString);
}else if(likeStatus.equals("2")){
}else {
detail_frown_count.setText(String.valueOf(Integer.parseInt(detailview_frown) + 1));
detailview_frown = detail_frown_count.getText().toString();
editor.putString("userDislike", String.valueOf(Integer.parseInt(userDislikeString) + 1));
editor.commit();
userDislikeString = pref.getString("userDislike", null);
TabMenu.userDislikeTextView.setText(userDislikeString);
}
likeStatus = "2";
new LikeTask().execute(likeStatus);
} });
if(commentClick.equals("1")){
comment_layout.setVisibility(View.VISIBLE);
}}
public class LikeTask extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
InputStream inputStream = null;
String result = "";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Global_Url.like_url);
try {
// Add your data
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(3);
nameValuePair.add(new BasicNameValuePair("jid",detailview_jokeid));
nameValuePair.add(new BasicNameValuePair("uid", userId));
nameValuePair.add(new BasicNameValuePair("status", likeStatus));
nameValuePair.add(new BasicNameValuePair("token", Token));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePair));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
inputStream = response.getEntity().getContent();
if (inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
}
return result;
}
private String convertInputStreamToString(InputStream inputStream)
throws IOException {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream));
String line = "";
String result = "";
while ((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
#Override
protected void onPostExecute(String result) {
try {
JSONObject jsono = new JSONObject(result);
String jarray = jsono.getString("status");
if(jarray.equals("0")){
Toast.makeText(getApplicationContext(), like_response, Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(getApplicationContext(),like_response, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}}}
#Override
public void onBackPressed() {
super.onBackPressed();
}}

cannot select radio button

I have a RadioGroup in which I have 5 RadioButton's. Also I have a button next. On click of next button the text of radiobuttons changes. It all works fine but some of the radio buttons are not selected. This is my xml file
public class SampleTestQuestionsActivity extends AppCompatActivity {
String totalques, timee, namee, idd;
String strServerResponse;
ProgressDialog nDialog;
ConnectionDetector cd;
Pojo pojo;
SamplePaperPojo samplePaperPojo;
RadioButton s_rb_1, s_rb_2, s_rb_3, s_rb_4, s_rb_5;
RadioGroup s_rbgrp;
private Toolbar toolbar;
TextView s_section, s_time, s_question;
Button s_submit, s_next, s_previous;
private CountDownTimer countDownTimer;
private boolean timerHasStarted = false;
long startTime;
private final long interval = 1 * 1000;
final Context context = this;
ArrayList<String> al_que_title;
ArrayList<String> al_que_id;
ArrayList<String> al_ans1;
ArrayList<String> al_ans2;
ArrayList<String> al_ans3;
ArrayList<String> al_ans4;
ArrayList<String> al_ans5;
ArrayList<String> al_correct;
ArrayList<String> al_exp;
ArrayList<String> al_desc;
String submitQuestionId;
ArrayList<SamplePaperPojo> sampleTest;
RadioButton selectedRbButton;
public static int inc = 0;
String correctAns;
ArrayList<String> selectedAns;
int selectedpos;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sample_test_questions);
toolbar = (Toolbar) findViewById(R.id.app_bar);
toolbar.setTitle("Sample Tests");
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
al_que_title = new ArrayList<String>();
al_que_id = new ArrayList<String>();
al_ans1 = new ArrayList<String>();
al_ans2 = new ArrayList<String>();
al_ans3 = new ArrayList<String>();
al_ans4 = new ArrayList<String>();
al_ans5 = new ArrayList<String>();
al_correct = new ArrayList<String>();
al_exp = new ArrayList<String>();
al_desc = new ArrayList<String>();
selectedAns = new ArrayList<String>();
Intent i =getIntent();
namee = i.getStringExtra("test_name");
totalques = i.getStringExtra("test_ques");
timee = i.getStringExtra("test_time");
idd = i.getStringExtra("test_id");
sampleTest = new ArrayList<SamplePaperPojo>();
Log.e("test_id", ""+idd);
Long ti = Long.valueOf(timee);
startTime = 1000*ti;
s_section = (TextView) findViewById(R.id.sampleSectionName);
s_time = (TextView) findViewById(R.id.sampleTimer);
s_question = (TextView) findViewById(R.id.sampleQuestion);
s_submit = (Button) findViewById(R.id.sampleSubmitAnswer);
s_next = (Button) findViewById(R.id.sampleNext);
s_previous = (Button) findViewById(R.id.samplePrevious);
s_rbgrp = (RadioGroup) findViewById(R.id.s_rbgrp);
s_rb_1 = (RadioButton) findViewById(R.id.SA);
s_rb_2 = (RadioButton) findViewById(R.id.SB);
s_rb_3 = (RadioButton) findViewById(R.id.SC);
s_rb_4 = (RadioButton) findViewById(R.id.SD);
s_rb_5 = (RadioButton) findViewById(R.id.SE);
countDownTimer = new MyCountDownTimer(startTime, interval);
s_time.setText(s_time.getText() + String.valueOf(startTime / 1000));
new NetCheck().execute();
s_next.setVisibility(View.GONE);
s_previous.setVisibility(View.GONE);
s_submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int index_selected = s_rbgrp.indexOfChild(s_rbgrp
.findViewById(s_rbgrp.getCheckedRadioButtonId()));
// get selected radio button from radioGroup
int selectedId = s_rbgrp.getCheckedRadioButtonId();
if (selectedId==-1){
AlertDialog alertDialog = new AlertDialog.Builder(
SampleTestQuestionsActivity.this).create();
alertDialog.setMessage("Please select atleast one answer.");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
s_next.setVisibility(View.VISIBLE);
}
});
s_next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
submitQuestionId = al_que_id.get(inc).toString();
s_rb_1.setTextColor(Color.parseColor("#000000"));
s_rb_2.setTextColor(Color.parseColor("#000000"));
s_rb_3.setTextColor(Color.parseColor("#000000"));
s_rb_4.setTextColor(Color.parseColor("#000000"));
s_rb_5.setTextColor(Color.parseColor("#000000"));
int selectedId = s_rbgrp.getCheckedRadioButtonId();
selectedRbButton = (RadioButton) findViewById(selectedId);
selectedRbButton.setChecked(false);
inc = inc + 1;
s_question.setText("" + al_que_title.get(inc).toString());
s_rb_1.setText("" + al_ans1.get(inc).toString());
s_rb_2.setText("" + al_ans2.get(inc).toString());
s_rb_3.setText("" + al_ans3.get(inc).toString());
s_rb_4.setText("" + al_ans4.get(inc).toString());
s_rb_5.setText("" + al_ans5.get(inc).toString());
s_next.setVisibility(View.GONE);
}
});
}
private class NetCheck extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
nDialog = new ProgressDialog(SampleTestQuestionsActivity.this);
nDialog.setMessage("Loading..");
nDialog.setTitle("Please Wait");
nDialog.setIndeterminate(false);
nDialog.setCancelable(true);
nDialog.show();
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Log.e("Post exec calleld", "dfds");
nDialog.dismiss();
s_question.setText("" + al_que_title.get(inc).toString());
s_rb_1.setText("" + al_ans1.get(inc).toString());
s_rb_2.setText("" + al_ans2.get(inc).toString());
s_rb_3.setText("" + al_ans3.get(inc).toString());
s_rb_4.setText("" + al_ans4.get(inc).toString());
s_rb_5.setText("" + al_ans5.get(inc).toString());
countDownTimer.start();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
cd = new ConnectionDetector(getApplicationContext());
if (!cd.isConnectingToInternet()) {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(
new Runnable() {
#Override
public void run() {
AlertDialog alertDialog = new AlertDialog.Builder(
SampleTestQuestionsActivity.this).create();
alertDialog.setMessage("Error connecting to internet.");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
}
);
}
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpRequest = new HttpPost(
"http://url");
httpRequest.setHeader("Content-Type", "application/json");
SharedPreferences preff = getSharedPreferences(
"MyPref", MODE_PRIVATE);
String userid = preff.getString("id", null);
Log.e("Student id", "" + userid);
JSONObject json = new JSONObject();
json.put("mocktest_id", idd);
json.put("section_id", 1);
Log.e("JSON Object", json.toString());
StringEntity se = new StringEntity(json.toString());
se.setContentEncoding("UTF-8");
se.setContentType("application/json");
httpRequest.setEntity(se);
HttpResponse httpRes = httpClient.execute(httpRequest);
java.io.InputStream inputStream = httpRes.getEntity()
.getContent();
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream);
BufferedReader reader = new BufferedReader(inputStreamReader);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
inputStream.close();
strServerResponse = sb.toString();
Log.e("Server Response", "" + strServerResponse.toString());
if (strServerResponse != null) {
try {
JSONArray arr1 = new JSONArray(strServerResponse);
JSONObject jsonObj1 = arr1.getJSONObject(0);
samplePaperPojo = new SamplePaperPojo();
for (int i = 0; i < arr1.length(); i++) {
JSONObject jobjj11 = arr1
.getJSONObject(i);
String qq_id = jobjj11.optString("id");
String qq_title = jobjj11.optString("title");
String qq_des = jobjj11.optString("description");
String ans_a = jobjj11.optString("ans_a");
String ans_b = jobjj11.optString("ans_b");
String ans_c = jobjj11.optString("ans_c");
String ans_d = jobjj11.optString("ans_d");
String ans_e = jobjj11.optString("ans_e");
String right_ans = jobjj11.optString("right_ans");
String explanation = jobjj11.optString("explanation");
samplePaperPojo.setSampleQuesId(qq_id);
samplePaperPojo.setSampleQuesTitle(qq_title);
samplePaperPojo.setSampleAns1(ans_a);
samplePaperPojo.setSampleAns2(ans_b);
samplePaperPojo.setSampleAns3(ans_c);
samplePaperPojo.setSampleAns4(ans_d);
samplePaperPojo.setSampleAns5(ans_e);
samplePaperPojo.setSampleRightAns(right_ans);
samplePaperPojo.setSampleQuesDescription(qq_des);
samplePaperPojo.setSampleExplaination(explanation);
sampleTest.add(samplePaperPojo);
al_que_id.add(qq_id);
al_que_title.add(qq_title);
al_ans1.add(ans_a);
al_ans2.add(ans_b);
al_ans3.add(ans_c);
al_ans4.add(ans_d);
al_ans5.add(ans_e);
al_correct.add(right_ans);
al_exp.add(explanation);
al_desc.add(qq_des);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler",
"Couldn't get any data from the url");
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
}
The radio button which I previously selected is not selected when the text is changed after i click on next button. Please help
You should replace:
int selectedId = s_rbgrp.getCheckedRadioButtonId();
selectedRbButton = (RadioButton) findViewById(selectedId);
selectedRbButton.setChecked(false);
with:
s_rbgrp.clearCheck();

Response:wrong. [User registration via android app using http post not working]

I was able to successfully make login work. Now, I am stuck up with registration. Response is wrong.
public class Register extends Activity implements OnClickListener{
private String mTitle = "Write.My.Action";
private static final String LOGTAG = "tag";
public EditText fullname, email, password;
private Button register;
private ProgressDialog mDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
getActionBar().setTitle(mTitle);
fullname = (EditText) findViewById(R.id.fullname);
email = (EditText) findViewById(R.id.editText2);
password = (EditText) findViewById(R.id.editText1);
register = (Button) findViewById(R.id.button1);
register.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
mDialog = new ProgressDialog(Register.this);
mDialog.setMessage("Attempting to Register...");
mDialog.setIndeterminate(false);
mDialog.setCancelable(false);
mDialog.show();
new Thread(new Runnable() {
#Override
public void run() {
register();
}
}).start();
}
}
void register() {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("myurl");
System.out.println("httpPost is: " + httpPost);
String fullname_input = fullname.getText().toString().trim();
String email_input = email.getText().toString().trim();
String password_input = password.getText().toString().trim();
//adding data into list view so we can make post over the server
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair("fullname", fullname_input));
nameValuePair.add(new BasicNameValuePair("email", email_input));
nameValuePair.add(new BasicNameValuePair("password", password_input));
System.out.println("namevaluepair is: " + nameValuePair);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
//execute http post resquest
HttpResponse httpResponse = httpClient.execute(httpPost);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpClient.execute(httpPost, responseHandler);
System.out.println("Response is: " + response);
runOnUiThread(new Runnable() {
#Override
public void run() {
mDialog.dismiss();
}
});
if(response.equalsIgnoreCase("Signed Up")){
runOnUiThread(new Runnable() {
#Override
public void run() {
startActivity(new Intent(Register.this, Registration_Success.class));
}
});
}else {
showAlert();
}
} catch (Exception e) {
mDialog.dismiss();
Log.i(LOGTAG, "Exception found"+ e.getMessage());
}
}
public void showAlert(){
Register.this.runOnUiThread(new Runnable() {
#Override
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(Register.this);
builder.setTitle("Registration Error");
builder.setMessage("Please, try registration again!")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
}
Please Note: Every activities are registered in Manifest, INTERNET permission also included.
php file:
include "dbconnection.php";
$fullname = $_POST['fullname'];
$email = $_POST['email'];
$password = $_POST['password'];
$insert_data = "INSERT INTO register
Values ('', '$fullname', '$email', '$password')";
$insert_result = mysql_query($insert_data);
//echo "Signed Up";
if($insert_result){
echo "Signed Up";
}
else{
echo "wrong!";
}
I don't understand why it keeps on saying Response is : Wrong. Tired of spending almost a day .. I am here seeking help.
Excuse me if my questions seems naive.
Thank you in advance.
try below code:-
HttpResponse httpResponse = httpClient.execute(httpPost);
if (httpResponse != null)
{
InputStream in = httpResponse.getEntity().getContent();
result = ConvertStreamToString.convertStreamToString(in);
// System.out.println("result =>" + result);
}
convertStreamToString method
public String convertStreamToString(InputStream is)
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try
{
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
is.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
return sb.toString();
}
do not under stand :-
HttpResponse httpResponse = httpClient.execute(httpPost); // getting response from server
// where you use this response and why using below line or whats the benefit of below line
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpClient.execute(httpPost, responseHandler);
Follow that tutorial very usefull, and clear how to work on json webservices with android.
How to connect Android with PHP, MySQL
Try this code using AsyncTask
public class Register extends Activity implements OnClickListener{
private String mTitle = "Write.My.Action";
private static final String LOGTAG = "tag";
public EditText fullname, email, password;
private Button register;
private ProgressDialog mDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
getActionBar().setTitle(mTitle);
fullname = (EditText) findViewById(R.id.fullname);
email = (EditText) findViewById(R.id.editText2);
password = (EditText) findViewById(R.id.editText1);
register = (Button) findViewById(R.id.button1);
register.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
mDialog = new ProgressDialog(Register.this);
mDialog.setMessage("Attempting to Register...");
mDialog.setIndeterminate(false);
mDialog.setCancelable(false);
mDialog.show();
new RegisterUser().execute();
}
}
public class RegisterUser extends AsyncTask<Void, Void, String>
{
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("myurl");
System.out.println("httpPost is: " + httpPost);
String fullname_input = fullname.getText().toString().trim();
String email_input = email.getText().toString().trim();
String password_input = password.getText().toString().trim();
//adding data into list view so we can make post over the server
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair("fullname", fullname_input));
nameValuePair.add(new BasicNameValuePair("email", email_input));
nameValuePair.add(new BasicNameValuePair("password", password_input));
System.out.println("namevaluepair is: " + nameValuePair);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
//execute http post resquest
HttpResponse httpResponse = httpClient.execute(httpPost);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpClient.execute(httpPost, responseHandler);
System.out.println("Response is: " + response);
return response;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(response.equalsIgnoreCase("Signed Up")){
runOnUiThread(new Runnable() {
#Override
public void run() {
startActivity(new Intent(Register.this, Registration_Success.class));
}
});
}else {
showAlert();
}
}
}
public void showAlert(){
Register.this.runOnUiThread(new Runnable() {
#Override
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(Register.this);
builder.setTitle("Registration Error");
builder.setMessage("Please, try registration again!")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
}
Hope this helps you!!!
If its not working please let me know i will try to help more...
Try using Volley if not. It's faster than the ussual HTTP connection classes.
Example:
RequestQueue queue = Volley.newRequestQueue(this);
String url = "url";
JSONObject juser = new JSONObject();
try {
juser.put("locationId", locID);
juser.put("email", email_input);
juser.put("password", password_input);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST, url, juser, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// TODO Auto-generated method stub
txtDisplay.setText("Response => "+response.toString());
findViewById(R.id.progressBar1).setVisibility(View.GONE);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
}
});
queue.add(jsObjRequest);
Like #Andrew T suggested , I am posting my solution.
The mysql_error()helped me debug the issue. mysql_error() displayed in the Logcat that "register table is not found" .. but the table name is registers. I was missing "s" at the end.
$fullname = $_POST['fullname'];
$email = $_POST['email'];
$password = $_POST['password'];
$insert_data = "INSERT INTO registers(id, fullname, email, password)
Values ('','$fullname', '$email', '$password')";
$insert_result = mysql_query($insert_data) or die(mysql_error());
//echo "Signed Up";
if($insert_result){
echo "Signed Up";
}
else{
echo "wrong!";
}
Everything worked perfect after that. Again, thank you all for your time and solutions. Everyone's suggestions are great, but I can not accept any answer at this point.. sorry:(

Retrieving data in offline mode

I have some data on the internet for each specific longitude and latitude. If a user inputs a particular latitude and longitude, the data is downloaded from the web and then used in further calculation. I want to save that data so that the next time the user inputs the same latitude and longitude, It bypasses the web connectivity and proceeds with the existing data.
My Input Class:
public class OpTilt extends Activity implements OnClickListener {
EditText latitude, longitude;
Button go;
String data1, data2, link, link1;
double dat1, dat2;
TextView gps;
SharedPreferences dataurl;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.optilt);
initialize();
go.setOnClickListener(this);
}
private void initialize() {
// TODO Auto-generated method stub
go = (Button) findViewById(R.id.loaddata);
latitude = (EditText) findViewById(R.id.lat);
longitude = (EditText) findViewById(R.id.lon);
dataurl = getSharedPreferences("url", 0);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
data1 = longitude.getText().toString();
data2 = latitude.getText().toString();
dat1 = Double.parseDouble(data1);
dat2 = Double.parseDouble(data2);
link = ("http://www.otilt.com/api.php?lat=" + dat2 + "&lon=" + dat1);
SharedPreferences.Editor editor = dataurl.edit();
editor.putString("key", link);
editor.commit();
Intent i = new Intent(OpTilt.this, DataRetrieve.class);
startActivity(i);
}
}
My Parsing Class:
public class DataRetrieve extends Activity {
HttpClient client;
String URL, re, element;
JSONObject json, getjson;
int i, j, statusCode;
HttpGet httpget;
HttpResponse response;
HttpEntity entity;
InputStream is;
BufferedReader reader;
StringBuilder sb, sb1;
WakeLock w;
SharedPreferences getinput, passjson;
ProgressDialog pd;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
w = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "tag");
super.onCreate(savedInstanceState);
w.acquire();
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.dataretrieve);
// Bundle gotBasket = getIntent().getExtras();
// URL = gotBasket.getString("key");
getinput = getSharedPreferences("url", 0);
URL = getinput.getString("key", null);
Read r = new Read();
r.execute();
}
public class Read extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
pd = new ProgressDialog(DataRetrieve.this);
pd.setTitle("Processing...");
pd.setMessage("Please wait.");
pd.setCancelable(false);
pd.setIndeterminate(true);
pd.show();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
re = null;
is = null;
json = null;
try {
client = new DefaultHttpClient();
httpget = new HttpGet(URL);
response = client.execute(httpget);
entity = response.getEntity();
is = entity.getContent();
statusCode = response.getStatusLine().getStatusCode();
} catch (Exception e) {
statusCode = -1;
Log.e("log_tag", "Erro http " + e.toString());
}
if (statusCode == 200) {
try {
reader = new BufferedReader(new InputStreamReader(is,
"UTF-8"), 8);
sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
re = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Erro conversão " + e.toString());
}
}
return re;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
pd.dismiss();
try {
json = new JSONObject(result);
getjson = json.getJSONObject("Solar");
String H[] = new String[getjson.length()];
for (i = 0, j = 1; i < getjson.length(); i++, j++) {
H[i] = getjson.getString("" + j);
}
Bundle bundle = new Bundle();
bundle.putStringArray("key1", H);
Intent f = new Intent(DataRetrieve.this, Calculator.class);
f.putExtras(bundle);
startActivity(f);
}
catch (JSONException e) {
Log.e("log_tag", "Erro dados " + e.toString());
}
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
w.release();
finish();
}
}
So, how can I achieve my goal?

how to print value from out of main method toinside main method [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
how to access value which is out of main class? i want to print value of elementarytxtview
in main class in parameter but is print null value of in parameter i want to pass elementarytextview value in parameter to other activity
public class HomeMenu extends Activity {
ImageButton imgNews, imgContact, imgSetting;
ListView listMainMenu;
ListView Middleschoollist, HighSchoollist, Atipicalschoollist;
String status;
firstscreenadapter mma;
String SelectMenuAPI;
String SelectMenuAPI2;
String url1;
String elementry;
// String High;
String message;
TextView Elementarytxt, Middletxt, Hightxt, Atypicaltxt;
static ArrayList<Long> Category_ID = new ArrayList<Long>();
static ArrayList<String> Category_name = new ArrayList<String>();
String elementarytxtview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.firstscreenfinal);
ExpandableHeightListView listMainMenu = (ExpandableHeightListView)
findViewById(R.id.listMainMenu11);
ExpandableHeightListView Middleschoollist = (ExpandableHeightListView)
findViewById(R.id.listMainMenu22);
ExpandableHeightListView HighSchoollist = (ExpandableHeightListView)
findViewById(R.id.listMainMenu33);
ExpandableHeightListView Atipicalschoollist = (ExpandableHeightListView)
findViewById(R.id.listMainMenu44);
Elementarytxt = (TextView) findViewById(R.id.Elementaryschool);
Middletxt = (TextView) findViewById(R.id.MiddleSchool);
Hightxt = (TextView) findViewById(R.id.HighSchool);
Atypicaltxt = (TextView) findViewById(R.id.AtipicalSchool);
mma = new firstscreenadapter(this);
if (!Utils.isNetworkAvailable(HomeMenu.this)) {
Toast.makeText(HomeMenu.this, "NO NETWORK Available",
Toast.LENGTH_SHORT).show();
}
if (!Utils.isUserOnline(this)) {
Toast.makeText(this, "No NETWORK", Toast.LENGTH_LONG).show();
}
url1 = "http://198.57.208.46/~school/ajax.php?action=get_school";
listMainMenu.setAdapter(mma);
Middleschoollist.setAdapter(mma);
HighSchoollist.setAdapter(mma);
Atipicalschoollist.setAdapter(mma);
listMainMenu.setExpanded(true);
Middleschoollist.setExpanded(true);
HighSchoollist.setExpanded(true);
Atipicalschoollist.setExpanded(true);
Toast.makeText(this, elementarytxtview, Toast.LENGTH_SHORT).show();
listMainMenu.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
Intent iMenuList = new Intent(HomeMenu.this,
SecondStep.class);
iMenuList.putExtra("category_name",xxx.xxx.xxxx/~school/index.php
/api/index/getschools?mg="+ Category_name.get(position)+ "&sl="+elementarytxtview);
startActivity(iMenuList);
}
});
parseJSONData();
}
void clearData() {
Category_ID.clear();
Category_name.clear();
}
public void parseJSONData() {
SelectMenuAPI = Utils.Homemenu2;
SelectMenuAPI2 = Utils.Homemenu;
clearData();
try {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams
.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(SelectMenuAPI);
HttpResponse response = client.execute(request);
InputStream atomInputStream = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(
atomInputStream));
String line;
String str = "";
while ((line = in.readLine()) != null) {
str += line;
}
HttpClient client2 = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client2.getParams(),
15000);
HttpConnectionParams.setSoTimeout(client2.getParams(), 15000);
HttpUriRequest request2 = new HttpGet(SelectMenuAPI2);
HttpResponse response2 = client2.execute(request2);
InputStream atomInputStream2 = response2.getEntity().getContent();
BufferedReader in2 = new BufferedReader(new InputStreamReader(
atomInputStream2));
String line2;
String str2 = "";
while ((line2 = in2.readLine()) != null) {
str2 += line2;
}
JSONObject json3 = new JSONObject(str2);
// message = json2.getString("message");
status = json3.getString("status");
if (status.equals("1")) {
JSONArray school2 = json3.getJSONArray("data");
String[] mVal = new String[school2.length()];
for (int i = 0; i < school2.length(); i++) {
mVal[i] =
school2.getJSONObject(i).getString("title");
Elementarytxt.setText(mVal[0]);
Middletxt.setText(mVal[1]);
Hightxt.setText(mVal[2]);
Atypicaltxt.setText(mVal[3]);
}
elementarytxtview = mVal[0];
}
JSONObject json2 = new JSONObject(str);
// message = json2.getString("message");
status = json2.getString("status");
if (status.equals("1")) {
// JSONObject data = json.getJSONObject("data");
JSONArray school = json2.getJSONArray("data");
for (int i = 0; i < school.length(); i++) {
JSONObject object = school.getJSONObject(i);
//
Category_ID.add(Long.parseLong(object.getString("id")));
Category_ID.add((long) i);
Category_name.add(object.getString("title"));
}
} else {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
// IOConnect = 1;
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
elementarytxtview is not initialized before you try to show it via Toast. At first you need to put some value in it.
I'm not a 100% sure of what you mean.
But if you want to access variables easily between classes, you should make the String elementarytxtview; public static
Thereby: public static String elementarytxtview;
What that means is basically that the variable is shared and can be used between all classes. Just by writing HomeMenu.elementarytxtview; in your case.
You are showing the Toast in the onCreate method which runs before your parseJSONData() method. You haven't initialized String elementarytxtview therefore it will show null because you only declared the variable.

Categories

Resources