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(....)
Related
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;
}
here is my doInbackground code from a class that extends Asynctask
protected String doInBackground(String... args) {
List<NameValuePair> paramss = new ArrayList<NameValuePair>();
paramss.add(new BasicNameValuePair(TAG_EMAIL, emailMember));
JSONObject json = parser.makeHttpRequest(url_get_pembayaran, "POST", paramss);
Log.d("shopping chart", json.toString());
return json.toString();
}
actually in always work at another code
this is my oncreate code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bayar);
txt_total_harga = (TextView) findViewById(R.id.txt_total_harga);
txt_ongkos_kirim = (TextView) findViewById(R.id.txt_ongkos_kirim);
txt_jumlah_barang = (TextView) findViewById(R.id.txt_jumlah_barang);
txt_status = (TextView) findViewById(R.id.txt_status);
btnBayar = (Button) findViewById(R.id.btnBayarSemua);
Intent ambil = getIntent();
idChart = ambil.getStringExtra("idShopping");
prefs = getSharedPreferences("login", Context.MODE_PRIVATE);
emailMember = prefs.getString("emailMember", "");
new DetailSC().execute();
}
this is my class that extends to Asynctask
class DetailSC extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... args) {
List<NameValuePair> paramss = new ArrayList<NameValuePair>();
paramss.add(new BasicNameValuePair(TAG_EMAIL, emailMember));
JSONObject json = parser.makeHttpRequest(url_get_pembayaran, "POST", paramss);
Log.d("shopping chart", json.toString());
return json.toString();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
pDialog.dismiss();
pDialog = null;
try{
JSONObject json = new JSONObject(result);
int success = json.getInt(TAG_SUCCESS);
if(success == 1){
shopping_detail = json.getJSONArray(TAG_SHOPPING);
JSONObject jObject = shopping_detail.getJSONObject(0);
int totalHarga = jObject.getInt(TAG_TOTAL_HARGA);
int berat = json.getInt(TAG_BERAT);
String ongkos = json.getString(TAG_ONGKOS_KIRIM);
int ongkosK = Integer.parseInt(ongkos);
totalHarga = ( berat * ongkosK ) / 1000;
txt_jumlah_barang.setText(jObject.getString(TAG_JUMLAH_BARANG));
txt_ongkos_kirim.setText(ongkos);
txt_status.setText(jObject.getString(TAG_STATUS));
txt_total_harga.setText("IDR " + totalHarga);
}
}catch(JSONException ex){
ex.printStackTrace();
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Bayar.this);
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.setMessage("Downloading Data . . .");
pDialog.show();
}
}
the error in logcat is :
eror parsing data org.json.JSONException : value email of type java.lang.String cannot be converted to JSONObject
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.
I want to use webservice to get data from after click on my button(button1)unfortunatly stopped I'm using json my debugger is not coming onclick view and my json is not giving response.
JSONParser jsonParser = new JSONParser();
private static final String about = "about";
private static String url = "http://www.mydomain/staticinfo";
private static final String TAG_SUCCESS = "id";
private static final String TAG_SUCCESS1="success";
#SuppressLint("NewApi")
protected void onCreate(Bundle savedInstanceState) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads().detectDiskWrites().detectNetwork()
.penaltyLog().build());
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButton();
}
public void action(View v)
{
if(v.getId()==R.id.button1)
new aboutAccess().execute();
else
Toast.makeText(this, "This is demo for smlsolution", Toast.LENGTH_LONG).show();
}
class aboutAccess extends AsyncTask<String, String, String>{
private String id;
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
//String url = "http://10.0.2.2/about.php";
List<NameValuePair> params = new ArrayList<NameValuePair>();
String ID="1";
params.add(new BasicNameValuePair("id ","ID"));
JSONObject json = jsonParser.makeHttpRequest(url,"POST", params);
Log.d("Create Response", json.toString());
try{
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
flag=0;
String abt=json.getString(about);
Intent i = new Intent(getApplicationContext(),About.class);
i.putExtra("about", abt);
startActivity(i);
}
else{
flag=1;
}
}
catch (JSONException e){
e.printStackTrace();
System.out.println(e.toString());
}
// TODO Auto-generated method stub
return null;
}
protected void onPostExecute(String file_url){
pDialog.dismiss();
if(flag==1)
Toast.makeText(MainActivity.this,"Data Not Found", Toast.LENGTH_LONG).show();
}
}
Your app is crashing because you are doing Activity switching operations in the doInBackground(). Change the following piece of code from doInBackground() to onPostExecute(),
Intent i = new Intent(getApplicationContext(),AboutUs.class);
startActivity(i);
finish();
Do something like below,
protected void onPostExecute(String file_url) {
pDialog.dismiss();
if(flag==1)
Toast.makeText(MainActivity.this,"Please Enter Correct informations",Toast.LENGTH_LONG).show();
else{
Intent i = new Intent(getApplicationContext(),AboutUs.class);
startActivity(i);
finish();
}
}
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();
}
}
}