i want to pass my id into another activity. can you show me how? i try search in google but nothing can help me. i hope that you can help me a little. i must be great if you can help me. i'm stuck with this problem for 3 days. makes me confused.
this is my code for pass :
private ProgressDialog mProgressDialog;
private static final String TAG_SUCCESS = "success";
JSONParser jsonParser = new JSONParser();
EditText inputfirstname,
inputmiddlename,
inputlastname,
inputaliasname,
inputcitybirth,
inputyearbirth;
RadioGroup gender;
RadioButton mr,mrs;
private static final String TAG_ID = "ID_Person";
private static String url_create_person ="http://172.18.0.20/person_new_xml.php";
private Spinner date,month,year;
Button saveperson,cancelperson;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.newperson);
inputfirstname = (EditText) findViewById(R.id.newfirstname);
inputmiddlename = (EditText) findViewById(R.id.newmiddlename);
inputlastname = (EditText) findViewById(R.id.newlastname);
inputaliasname = (EditText) findViewById(R.id.newaliasname);
gender = (RadioGroup)findViewById(R.id.jekel);
inputcitybirth = (EditText) findViewById(R.id.newcitybirth);
date = (Spinner) findViewById(R.id.spinnerdate);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource
(this, R.array.date_array, android.R.layout.simple_spinner_dropdown_item);
date.setAdapter(adapter);
month = (Spinner) findViewById(R.id.spinnermonth);
ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource
(this, R.array.month_array, android.R.layout.simple_spinner_dropdown_item);
month.setAdapter(adapter2);
year = (Spinner) findViewById(R.id.spinneryear);
ArrayAdapter<CharSequence> adapter3 = ArrayAdapter.createFromResource
(this, R.array.year_array, android.R.layout.simple_spinner_dropdown_item);
year.setAdapter(adapter3);
cancelperson = (Button) findViewById(R.id.btncancelnewperson);
saveperson = (Button) findViewById(R.id.btnsnextnewperson);
saveperson.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new CreatePerson().execute();
}
});
}
private class CreatePerson extends AsyncTask<String, String, String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setMessage("Creating Product..");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setCancelable(true);
mProgressDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
String select = null;
switch (gender.getCheckedRadioButtonId())
{
case R.id.mr:
select="Mr.";
break;
case R.id.mrs:
select="Mrs.";
default:
break;
}
String firstname = inputfirstname.getText().toString();
String middlename = inputmiddlename.getText().toString();
String lastname = inputlastname.getText().toString();
String aliasname = inputaliasname.getText().toString();
String city = inputcitybirth.getText().toString();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("FirstName", firstname));
params.add(new BasicNameValuePair("MiddleName", middlename));
params.add(new BasicNameValuePair("LastName", lastname));
params.add(new BasicNameValuePair("AliasName", aliasname));
params.add(new BasicNameValuePair("Gender", select));
params.add(new BasicNameValuePair("CityBirth", city));
params.add(new BasicNameValuePair("DateBirth", date.getSelectedItem().toString()));
params.add(new BasicNameValuePair("MonthBirth", month.getSelectedItem().toString()));
params.add(new BasicNameValuePair("YearBirth", year.getSelectedItem().toString()));
JSONObject json = jsonParser.makeHttpRequest(url_create_person, "POST", params);
Log.d("Create Response", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
String id = ((Button) findViewById(R.id.btnsnextnewperson)).getText().toString();
Intent i = new Intent(getApplicationContext(),CreateUser.class);
i.putExtra(TAG_ID, id);
startActivity(i);
finish();
} else {
}
} catch (JSONException e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
mProgressDialog.dismiss();
}
}
}
and this is my code for receive :
private ProgressDialog mProgressDialog;
private static final String TAG_SUCCESS = "success";
JSONParser jsonParser = new JSONParser();
String ID;
//String Name;
private static final String TAG_Person = "person";
private static final String TAG_ID = "ID_Person";
TextView id;
EditText inputuser,inputpassword,inputanswer;
private Spinner question;
Button save;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.registeruser);
ID = getIntent().getStringExtra(TAG_ID);
id =(TextView) findViewById(R.id.textname);
inputuser = (EditText) findViewById(R.id.inputuser);
inputpassword = (EditText) findViewById(R.id.inputpassword);
inputanswer = (EditText) findViewById(R.id.inputanswer);
question = (Spinner) findViewById(R.id.questionspinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource
(this, R.array.securityquestion, android.R.layout.simple_spinner_dropdown_item);
question.setAdapter(adapter);
new User().execute();
save = (Button) findViewById(R.id.savebutton);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new Createuser().execute();
}
});
}
private class User extends AsyncTask<String, String, JSONArray>{
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(CreateUser.this);
mProgressDialog.setMessage("Loading products. Please wait...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
#Override
protected JSONArray doInBackground(String... param) {
// TODO Auto-generated method stub
JSONArray personobj = new JSONArray();
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("ID_Person", ID));
String url_product_detials = "http://172.18.0.20/get.php";
JSONObject json = jsonParser.makeHttpRequest(
url_product_detials, "GET", params);
Log.d("Single Person Details", json.toString());
personobj = json.getJSONArray(TAG_Person);
} catch (JSONException e) {
// TODO: handle exception
e.printStackTrace();
}
return personobj;
}
protected void onPostExecute(JSONArray personobj){
mProgressDialog.dismiss();
try {
for (int i = 0; i < personobj.length(); i++) {
JSONObject person;
person = personobj.getJSONObject(i);
String Id = person.getString("ID_Person");
id.setText(Id);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I will recommend to call the intent in onPostExecute of AsyncTask. Also store the text of the button in a string before going into doInBackground. The doInBackground is a seperate thread and can't communicate with Main UI Thread.
as berserk said,the doInBackground is a seperate thread that cant communicate with main UI Thread,so, as my recommedn,you should startActivity() in the onPostExecute.
just change to below
private class CreatePerson extends AsyncTask<String, String, String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setMessage("Creating Product..");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setCancelable(true);
mProgressDialog.show();
//String select = null;//member var of outside class
switch (gender.getCheckedRadioButtonId())
{
case R.id.mr:
select="Mr.";
break;
case R.id.mrs:
select="Mrs.";
default:
break;
}
String firstname = inputfirstname.getText().toString();
String middlename = inputmiddlename.getText().toString();
String lastname = inputlastname.getText().toString();
String aliasname = inputaliasname.getText().toString();
String city = inputcitybirth.getText().toString();
//List<NameValuePair> params = new ArrayList<NameValuePair>();//member var of outside class
params.add(new BasicNameValuePair("FirstName", firstname));
params.add(new BasicNameValuePair("MiddleName", middlename));
params.add(new BasicNameValuePair("LastName", lastname));
params.add(new BasicNameValuePair("AliasName", aliasname));
params.add(new BasicNameValuePair("Gender", select));
params.add(new BasicNameValuePair("CityBirth", city));
params.add(new BasicNameValuePair("DateBirth", date.getSelectedItem().toString()));
params.add(new BasicNameValuePair("MonthBirth", month.getSelectedItem().toString()));
params.add(new BasicNameValuePair("YearBirth", year.getSelectedItem().toString()));
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// JSONObject json = null//member var of outside class
json = jsonParser.makeHttpRequest(url_create_person, "POST", params);
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
if(mProgressDialog != null && mProgressDialog.isShow()){
mProgressDialog.dismiss();
}
Log.d("Create Response", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
String id = ((Button) findViewById(R.id.btnsnextnewperson)).getText().toString();
Intent i = new Intent(getApplicationContext(),CreateUser.class);
i.putExtra(TAG_ID, id);
startActivity(i);
finish();
} else {
}
} catch (JSONException e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
Related
This question already has answers here:
Method getText() must be called from the UI Thread (Android Studio)
(5 answers)
Closed 6 years ago.
I'm making the register in Android Studio, and I found a problem on
String name = names. getText (). toString ();
String address = address. getText (). toString ();
String telephone = telephone. getText (). toString ();
String username = user. getText (). toString ();
String password = pass. getText (). toString ();,
Possible solutions?
Here is my Activity code:
public class ActivityRegister extends Activity implements View.OnClickListener {
private EditText user, pass, nama, alamat, telpon;
private TextView t1;
private RadioButton rb1, rb2;
private Button mRegister;
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "http://10.0.2.2/coba/api/register.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.header)));
bar.setTitle("Register Distro App");
nama = (EditText) findViewById(R.id.nama);
alamat = (EditText) findViewById(R.id.alamat);
telpon = (EditText) findViewById(R.id.telpon);
user = (EditText) findViewById(R.id.username);
pass = (EditText) findViewById(R.id.password);
rb1=(RadioButton)findViewById(R.id.option1);
rb2=(RadioButton)findViewById(R.id.option2);
t1=(TextView)findViewById(R.id.TextView01);
mRegister = (Button)findViewById(R.id.register);
mRegister.setOnClickListener(this);
}
#Override
public void onClick(View v) {
new CreateUser().execute();
}
class CreateUser extends AsyncTask<String, String, String> {
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ActivityRegister.this);
pDialog.setMessage("Mendaftar Member...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
int success;
String namanya = nama.getText().toString();
String alamatnya = alamat.getText().toString();
String telponnya = telpon.getText().toString();
String username = user.getText().toString();
String password = pass.getText().toString();
if(rb1.isChecked() == true)
t1.setText(rb1.getText());
if(rb2.isChecked() == true)
t1.setText(rb2.getText());
if(rb1.isChecked() == false && rb2.isChecked() == false)
t1.setText("");
String jenkel = t1.getText().toString();
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
params.add(new BasicNameValuePair("nama", namanya));
params.add(new BasicNameValuePair("alamat", alamatnya));
params.add(new BasicNameValuePair("telpon", telponnya));
params.add(new BasicNameValuePair("jenkel", jenkel));
Log.d("request!", "starting");
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
Log.d("Register attempt", json.toString());
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("User Created!", json.toString());
finish();
return json.getString(TAG_MESSAGE);
}else{
Log.d("Register Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
if (file_url != null){
Toast.makeText(ActivityRegister.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
The reason is in AsyncTask behavior.
Methods onPreExecute(), onPostExecute are called from UI Thread.
But doInBackground() is called in separate thread.
The solution is to pass text parameters to AsyncTask#execute.
See: AsyncTask tutorial
You have a background thread but when you access UI components you have to access them through the man UI thread. You can do this by
youActivity.runOnUiThread(new Runnable() {
public void run() {
t1.setText(rb1.getText());
}
});
Error shows: FATAL EXCEPTION: AsyncTask #1
public class NewProductActivity extends Activity {
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText inputName;
EditText inputPrice;
EditText inputDesc;
private static String url_create_product = "http://127.0.0.1/android_connect/create_product.php";
private static final String TAG_SUCCESS = "success";
static List<String> citations = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_product);
inputName = (EditText) findViewById(R.id.inputName);
inputPrice = (EditText) findViewById(R.id.inputPrice);
inputDesc = (EditText) findViewById(R.id.inputDesc);
Button btnCreateProduct = (Button) findViewById(R.id.btnCreateProduct);
btnCreateProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// creating new product in background thread
new CreateNewProduct().execute();
}
});
}
class CreateNewProduct extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewProductActivity.this);
pDialog.setMessage("Creating Product..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
String name = inputName.getText().toString();
String price = inputPrice.getText().toString();
String description = inputDesc.getText().toString();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("price", price));
params.add(new BasicNameValuePair("description", description));
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
Log.d("Create Response", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
startActivity(i);
finish();
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
}
}
}
Move in your onPostExecute(....)
Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
startActivity(i);
finish();
Never call finish(); or Intent in doInBackground(....)
In my application I used autocompletetextview to retrieve data,the data which I display is using json,now autocompletetextview works well,but what I want is after getting name in my autocompletetextview I want to send id of category,but it sends name..following is my response..and my snippet code is here..Autocompletetextview not working
{
"category":
[
{
"id":"4",
"name":"cat1"
},
{
"id":"7",
"name":"aditya"}
]
}
Add_Catagory.java
public class MainActivity extends Activity {
private Button btns;
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
private MultiAutoCompleteTextView acTextView;
private static final String FEEDBACK_URL = "";
private static final String FEEDBACK_SUCCESS = "status";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
acTextView = (MultiAutoCompleteTextView) findViewById(R.id.autoComplete);
acTextView.setAdapter(new SuggestionAdapter(this,acTextView.getText().toString()));
acTextView.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
/* JsonParse jp=new JsonParse();
List<SuggestGetSet> list =jp.getParseJsonWCF(acTextView.getText().toString());
list.get(0).getId();*/
btns=(Button)findViewById(R.id.btn);
btns.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new AttemptLogin().execute();
}
});
}
class AttemptLogin extends AsyncTask<String, String, String> {
boolean failure = false;
private String catid;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Sending..");
pDialog.setIndeterminate(true);
// pDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.custom_progress));
pDialog.setCancelable(true);
pDialog.show();
}
#SuppressWarnings("unused")
#Override
protected String doInBackground(String...args) {
//Check for success tag
//int success;
Looper.prepare();
String pweighttype=acTextView.getText().toString();
try {
JsonParse jp=new JsonParse();
List<NameValuePair> params = new ArrayList<NameValuePair>();
List<SuggestGetSet> list =jp.getParseJsonWCF(acTextView.getText().toString());
for(int i = 0;i<list.size();i++){
if(list.get(i).getName().equals(acTextView.getText().toString()))
params.add(new BasicNameValuePair("parentid",list.get(i).getId()));
System.out.println("Su gayu server ma"+params);
catid=list.get(i).getId().toString();
}
System.out.println("Su catid"+catid);
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest (
FEEDBACK_URL, "POST", params);
//check your log for json response
Log.d("Login attempt", json.toString());
JSONObject jobj = new JSONObject(json.toString());
final String msg = jobj.getString("msg");
runOnUiThread(new Runnable()
{
#Override
public void run()
{
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_LONG).show();
}
});
return json.getString(FEEDBACK_SUCCESS);
}catch (JSONException e) {
e.printStackTrace();
}
return null;
}
// After completing background task Dismiss the progress dialog
protected void onPostExecute(String file_url) {
//dismiss the dialog once product deleted
pDialog.dismiss();
//parentcat.getText().clear();
}}
try this//modify doInBackground
try {
JsonParse jp=new JsonParse();
List<NameValuePair> params = new ArrayList<NameValuePair>();
List<SuggestGetSet> list =jp.getParseJsonWCF(acTextView.getText().toString());
for(int i = 0;i<list.length();i++){
if(list.get(i).getName().equals(acTextView.getText().toString()))
params.add(new BasicNameValuePair("parentid",list.get(i).getId()));
break;
}
I have a problem i need the token to transfer it to my SessionManagement class to compare it with the saved token , but in my onCreate it's always null ,i need a workaround to make my token not null in oncreate
please help.
here is my code
private static final String LOGIN_URL = "http://baymd.myterranet.com/api/auth";
private static final String TAG_SUCCESS = "code";
private static final String TAG_MESSAGE = "message";
private static final String TAG_DATA = "data";
private static final String TAG_TOKEN = "access_token";
JSONParser jsonParser = new JSONParser();
private EditText user, pass;
private Button mSubmit;
private ProgressDialog pDialog;
private String token, none,SavedToken;
SesionManagement session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
session=new SesionManagement(getApplicationContext());
HashMap<String, String> tokens = session.getUserDetails();
SavedToken = tokens.get(session.KEY_NAME);
if(token==null) {//This line
Log.d("TOKEN ====== ", "NULLL");
}
session.checkLogin(token, SavedToken);
user = (EditText) findViewById(R.id.inputEmail);
pass = (EditText) findViewById(R.id.inputPass);
mSubmit = (Button) findViewById(R.id.loginBtn);
mSubmit.setOnClickListener(this);
}
#Override
public void onClick(View v) {
new AttemptLogin().execute();
}
class AttemptLogin extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Attempting login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
int success;
String username = user.getText().toString();
String password = pass.getText().toString();
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", username));
params.add(new BasicNameValuePair("password", password));
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params, none);
success = json.getInt(TAG_SUCCESS);
if (success == 200) {
JSONObject c = json.getJSONObject(TAG_DATA);
token = c.getString(TAG_TOKEN);//The token wich is null in oncreate
Intent i = new Intent(Login.this, NavDraver.class);
i.putExtra("cjson", c.toString());
finish();
startActivity(i);
return json.getString(TAG_MESSAGE);
} else {
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
json.getString(TAG_MESSAGE);
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
session.createLoginSession(token);
Log.d("SAVED TOKEN",SavedToken);
pDialog.dismiss();
}
}
}
Try this:
token = c.optString(TAG_TOKEN, yourDefaultValueHere);
if(token == null){
token = ""; // or whatever you want to init here
}
Hope it helps.
When i insert my parsed data into the listview, the added items appear at the bottom i want to put them on top like on facebook new posts are added on top. here is my code:
I am retrieving my comments from a server. Pls help me out
This is the Readpost.java
private static final String TAG_SUCCESS = "success";
private static final String TAG_TITLE = "title";
private static final String TAG_POSTS = "posts";
private static final String TAG_POST_ID = "post_id";
private static final String TAG_USERNAME = "username";
private static final String TAG_MESSAGE = "message";
private JSONArray mComments = null;
private ArrayList<HashMap<String, String>> mCommentList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newsfeed);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
// loading the comments via AsyncTask
new LoadComments().execute();
}
public void addComment(View v) {
Intent i = new Intent(Readpost.this, Addpost.class);
startActivity(i);
}
/**
* Retrieves recent post data from the server.
*/
public void updateJSONdata() {
mCommentList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(READ_COMMENTS_URL);
try {
mComments = json.getJSONArray(TAG_POSTS);
for (int i = 0; i < mComments.length(); i++) {
JSONObject c = mComments.getJSONObject(i);
String title = c.getString(TAG_TITLE);
String content = c.getString(TAG_MESSAGE);
String username = c.getString(TAG_USERNAME);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TITLE, title);
map.put(TAG_MESSAGE, content);
map.put(TAG_USERNAME, username);
mCommentList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private void updateList() {
ListAdapter adapter = new SimpleAdapter(this, mCommentList,
R.layout.singlepost, new String[] { TAG_TITLE, TAG_MESSAGE,
TAG_USERNAME }, new int[] { R.id.title, R.id.message,
R.id.username });
setListAdapter(adapter);
ListView lv = getListView();
lv.scrollTo(0, 0);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
}
And this is the Addpost.java
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.addpost);
title = (EditText)findViewById(R.id.title);
message = (EditText)findViewById(R.id.message);
mSubmit = (Button)findViewById(R.id.submit);
mSubmit.setOnClickListener(this);
}
#Override
public void onClick(View v) {
new PostComment().execute();
}
class PostComment extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Addpost.this);
pDialog.setMessage("Posting...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String post_title = title.getText().toString();
String post_message = message.getText().toString();
try {
final SharedPreferences mSharedPreference= PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String value =(mSharedPreference.getString("username", "anon"));
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", value));
params.add(new BasicNameValuePair("title", post_title));
params.add(new BasicNameValuePair("message", post_message));
Log.d("request!", "starting");
JSONObject json = jsonParser.makeHttpRequest(
POST_COMMENT_URL, "POST", params);
Log.d("Post Comment attempt", json.toString());
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Comment Added!", json.toString());
finish();
return json.getString(TAG_MESSAGE);
}else{
Log.d("Comment Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null){
Toast.makeText(Addpost.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
Assuming you retain your ListAdapter as follows:
ListAdapter mAdapter;
You can add a new item like this.
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TITLE, "New Title");
map.put(TAG_MESSAGE, "new content");
map.put(TAG_USERNAME, "someone");
mCommentList.add(0, map);
mAdapter.notifyDatasetChanged();
Use this:
mCommentList.add(0, obj);
listAdapter.notifyDataSetChanged();
listView.scrollTo(0, 0);