This is a flowchart of what I want:
the image above is like a flowchart of what i want to create. i want to have first activity with buttons like 10 or so all will have
case 0:
Intent intent = new Intent(getActivity(), AActivity.class);
intent.putExtra("categoryId", 1);
intent.putExtra("title", Animal);
startActivity(intent);
break;
case 1:
Intent e = new Intent(getActivity(), AActivity.class);
e.putExtra("categoryId", 2);
e.putExtra("title", eletronics);
startActivity(e);
break;
case 2:
Intent f = new Intent(getActivity(), AActivity.class);
f.putExtra("categoryId", 3);
f.putExtra("title", fashion);
startActivity(f);
break;
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
include_once($_SERVER['DOCUMENT_ROOT']."/config/config.php");
$id= $_POST['id'];
// Create connection
$conn = new mysqli($host, $user, $pass, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM comments where comment_id = '$id'" ;
$result = $conn->query($sql);
if ($result->num_rows >0) {
while($row[] = $result->fetch_assoc()) {
$tem = $row;
$json = json_encode($tem);
}
} else {
echo "No Results Found.";
}
echo $json;
$conn->close();
}
?>
i need help in creating the second activity that will be in listview that will receive that from php and display it. so if button 1 is click it will fetch all data relating to id 1
my question is how will i implement the second activity which will receive the value fetch the values from mysql and display it as list view
this is the one i used in my app try if you can use it
package com.fruitmarket;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.SearchView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.SimpleBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.nostra13.universalimageloader.utils.StorageUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import Config.ConstValue;
import adapters.ProductsAdapter;
import imgLoader.AnimateFirstDisplayListener;
import imgLoader.JSONParser;
import util.ConnectionDetector;
import util.ObjectSerializer;
#SuppressWarnings("deprecation")
#SuppressLint("NewApi")
public class ProductsActivity2 extends ActionBarActivity{
public SharedPreferences settings;
public ConnectionDetector cd;
static ArrayList<HashMap<String, String>> products_array;
ProductsAdapter adapter;
ListView products_listview;
DisplayImageOptions options;
ImageLoaderConfiguration imgconfig;
ProgressDialog dialog;
TextView txtcount;
private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
HashMap<String, String> catMap;
#SuppressWarnings("unchecked")
#Override
protected void onCreate(Bundle savedInstanceState) {
settings = getSharedPreferences(ConstValue.MAIN_PREF, 0);
cd = new ConnectionDetector(getApplicationContext());
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_products);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
settings = getSharedPreferences(ConstValue.MAIN_PREF, 0);
cd=new ConnectionDetector(this);
File cacheDir = StorageUtils.getCacheDirectory(this);
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.loading)
.showImageForEmptyUri(R.drawable.loading)
.showImageOnFail(R.drawable.loading)
.cacheInMemory(true)
.cacheOnDisk(true)
.considerExifParams(true)
.displayer(new SimpleBitmapDisplayer())
.imageScaleType(ImageScaleType.NONE)
.build();
imgconfig = new ImageLoaderConfiguration.Builder(this)
.build();
ImageLoader.getInstance().init(imgconfig);
ArrayList<HashMap<String,String>> categoryArray = new ArrayList<HashMap<String,String>>();
try {
categoryArray = (ArrayList<HashMap<String,String>>) ObjectSerializer.deserialize(settings.getString("categoryname", ObjectSerializer.serialize(new ArrayList<HashMap<String,String>>())));
}catch (IOException e) {
e.printStackTrace();
}
catMap = new HashMap<String, String>();
catMap = categoryArray.get(getIntent().getExtras().getInt("position"));
products_array = new ArrayList<HashMap<String,String>>();
try {
products_array = (ArrayList<HashMap<String,String>>) ObjectSerializer.deserialize(settings.getString("products_"+catMap.get("id"), ObjectSerializer.serialize(new ArrayList<HashMap<String,String>>())));
}catch (IOException e) {
e.printStackTrace();
}
products_listview = (ListView)findViewById(R.id.listView1);
adapter = new ProductsAdapter(getApplicationContext(), products_array);
products_listview.setAdapter(adapter);
TextView txtTitle = (TextView)findViewById(R.id.catname);
txtTitle.setText(catMap.get("name"));
txtcount = (TextView)findViewById(R.id.textcount);
products_listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long id) {
// TODO Auto-generated method stub
try {
settings.edit().putString(getString(R.string.productsActivity),ObjectSerializer.serialize(products_array.get(position))).commit();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent intent = new Intent(ProductsActivity2.this, ProductdetailActivity.class);
intent.putExtra("position", position);
startActivity(intent);
}
});
new loadProductsTask().execute(true);
}
#Override
protected void onNewIntent(Intent intent) {
handleIntent(intent);
}
private void handleIntent(Intent intent) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
if (!query.equalsIgnoreCase("")) {
//use the query to search your data somehow
new loadProductsTask().execute(true);
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.products, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getComponentName()));
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
Intent intent = new Intent(ProductsActivity2.this,MainActivity.class);
startActivity(intent);
}
else if(id==R.id.action_viewcart){
//Intent intent = new Intent(ProductsActivity.this,ViewcartActivity.class);
//startActivity(intent);
}
else if(id == android.R.id.home){
finish();
}
return super.onOptionsItemSelected(item);
}
public class loadProductsTask extends AsyncTask<Boolean, Void, ArrayList<HashMap<String, String>>> {
JSONParser jParser;
JSONObject json;
String count;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
// TODO Auto-generated method stub
if (result!=null) {
//adapter.notifyDataSetChanged();
}
try {
settings.edit().putString("products_"+catMap.get("id"),ObjectSerializer.serialize(products_array)).commit();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
txtcount.setText(count);
adapter.notifyDataSetChanged();
super.onPostExecute(result);
}
#Override
protected void onProgressUpdate(Void... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
#Override
protected void onCancelled(ArrayList<HashMap<String, String>> result) {
// TODO Auto-generated method stub
super.onCancelled(result);
}
#Override
protected ArrayList<HashMap<String, String>> doInBackground(
Boolean... params) {
// TODO Auto-generated method stub
try {
jParser = new JSONParser();
if(cd.isConnectingToInternet())
{
String urlstring = ConstValue.JSON_PRODUCTS+"&id="+catMap.get("id");
if (Intent.ACTION_SEARCH.equals(getIntent().getAction())) {
String query = getIntent().getStringExtra(SearchManager.QUERY);
//use the query to search your data somehow
urlstring = urlstring + "&search="+query;
}
json = jParser.getJSONFromUrl(urlstring);
count = json.getString("count");
if (json.has("data")) {
if(json.get("data") instanceof JSONArray){
JSONArray jsonDrList = json.getJSONArray("data");
products_array.clear();
for (int i = 0; i < jsonDrList.length(); i++) {
JSONObject obj = jsonDrList.getJSONObject(i);
put_object(obj);
}
}else if(json.get("data") instanceof JSONObject){
put_object(json.getJSONObject("data"));
}
}
}else
{
Toast.makeText(ProductsActivity2.this,getString(R.string.internetconnection), Toast.LENGTH_LONG).show();
}
jParser = null;
json = null;
} catch (Exception e) {
// TODO: handle exception
return null;
}
return null;
}
public void put_object(JSONObject obj){
HashMap<String, String> map = new HashMap<String, String>();
try {
map.put("id", obj.getString("id"));
map.put("title", obj.getString("title"));
map.put("slug", obj.getString("slug"));
map.put("description", obj.getString("description"));
map.put("image", obj.getString("image"));
map.put("price", obj.getString("price"));
map.put("currency", obj.getString("currency"));
map.put("discount", obj.getString("discount"));
map.put("cod", obj.getString("cod"));
map.put("emi", obj.getString("emi"));
map.put("status", obj.getString("status"));
map.put("gmqty", obj.getString("gmqty"));
map.put("unit", obj.getString("unit"));
map.put("deliverycharge", obj.getString("deliverycharge"));
map.put("tax", obj.getString("tax"));
map.put("category_id", obj.getString("category_id"));
map.put("on_date", obj.getString("on_date"));
map.put("stock", obj.getString("stock"));
map.put("type", obj.getString("type"));
map.put("total_qty_stock", obj.getString("total_qty_stock"));
map.put("consume_qty_stock", obj.getString("consume_qty_stock"));
products_array.add(map);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Related
I am working on an Android app using InAppBilling. I recently moved the following code from my main Activity to an AsyncTask, as recommended by Google:
class GetItemList extends AsyncTask<Integer, Integer, Long> {
IInAppBillingService mService;
ServiceConnection mServiceConn = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
mService = null;
}
#Override
public void onServiceConnected(ComponentName name,
IBinder service) {
mService = IInAppBillingService.Stub.asInterface(service);
}
};
#Override
protected Long doInBackground(Integer... params) {
ArrayList<String> skuList = new ArrayList<String> ();
skuList.add("i001");
skuList.add("i002");
Bundle querySkus = new Bundle();
querySkus.putStringArrayList("ITEM_ID_LIST", skuList);
Bundle skuDetails = null;
try {
skuDetails = mService.getSkuDetails(3, getPackageName(), "inapp", querySkus);
int response = skuDetails.getInt("RESPONSE_CODE");
if (response == 0) {
ArrayList<String> responseList
= skuDetails.getStringArrayList("DETAILS_LIST");
for (String thisResponse : responseList) {
JSONObject object;
object = new JSONObject(thisResponse);
String sku = object.getString("productId");
String price = object.getString("price");
String mPremiumUpgradePrice;
String mGasPrice;
if (sku.equals("i001")) mPremiumUpgradePrice = price;
else if (sku.equals("i002")) mGasPrice = price;
}
}
} catch (RemoteException e) {
// TODO Auto-generated catch block
Log.d("Synch Billing", "Error Remote: " + e.getMessage());
e.printStackTrace();
}
catch (JSONException e) {
// TODO Auto-generated catch block
Log.d("Synch Billing", "Error JSON: " + e.getMessage());
e.printStackTrace();
}
return null;
}
}
My problem is that the call to getPackageName() (the first line of the try block) is giving the error, "The method getPackageName() is undefined for the task GetItemList." How do I call getPackageName() from within an AsyncTask? I've tried GetContextWrapper.getPackageName(), getApplicationContext.getPackageName(), and getResources.getPackageName().
Corrected code, based on mixel's answer below:
package com.myknitcards;
import java.util.ArrayList;
import org.json.JSONException;
import org.json.JSONObject;
import com.android.vending.billing.IInAppBillingService;
import android.app.Activity;
import android.content.ComponentName;
import android.content.ServiceConnection;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
public class AvailableCards extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_available_cards);
String packagename = this.getPackageName();
new GetItemList(packagename).execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.available_cards, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
class GetItemList extends AsyncTask<Integer, Integer, Long> {
private String pName;
GetItemList(String packagename){
pName = packagename;
}
IInAppBillingService mService;
ServiceConnection mServiceConn = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
mService = null;
}
#Override
public void onServiceConnected(ComponentName name,
IBinder service) {
mService = IInAppBillingService.Stub.asInterface(service);
}
};
#Override
protected Long doInBackground(Integer... params) {
ArrayList<String> skuList = new ArrayList<String> ();
skuList.add("i001");
skuList.add("i002");
Bundle querySkus = new Bundle();
querySkus.putStringArrayList("ITEM_ID_LIST", skuList);
Bundle skuDetails = null;
try {
skuDetails = mService.getSkuDetails(3, pName, "inapp", querySkus);
int response = skuDetails.getInt("RESPONSE_CODE");
if (response == 0) {
ArrayList<String> responseList
= skuDetails.getStringArrayList("DETAILS_LIST");
for (String thisResponse : responseList) {
JSONObject object;
object = new JSONObject(thisResponse);
String sku = object.getString("productId");
String price = object.getString("price");
String mPremiumUpgradePrice;
String mGasPrice;
if (sku.equals("i001")) mPremiumUpgradePrice = price;
else if (sku.equals("i002")) mGasPrice = price;
}
}
} catch (RemoteException e) {
// TODO Auto-generated catch block
Log.d("Synch Billing", "Error Remote: " + e.getMessage());
e.printStackTrace();
}
catch (JSONException e) {
// TODO Auto-generated catch block
Log.d("Synch Billing", "Error JSON: " + e.getMessage());
e.printStackTrace();
}
return null;
}
}
Add constructor to GetItemList that accepts packageName and assigns it to private field. Then use it in mService.getSkuDetails().
And when you instantiate GetItemList in your activity pass value that returned by getPackageName() to GetItemList constructor.
i want input date, but i dont know how to declare date in eclipse android
this my code
EditText txtdate;
and then
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_form_lelang);
txtdate = (EditText)findViewById(R.id.txtdate);
this code my asynctask thread
protected String doInBackground(String... params) {
param.add(new BasicNameValuePair("date", txtdate.getText().toString()));
where im write code declare txtdate (Date) ?
package com.example.lelangifan;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.lelangifan.Daftar;
import com.example.lelangifan.ServiceHandler;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class FormLelang extends Activity implements OnClickListener {
EditText txtjudul;
EditText txtharga;
EditText txtdate;
Button btncreate;
JSONArray tag_besar;
int success = 0;
int cek_username = 0;
AlertDialogManager alert = new AlertDialogManager();
private static String url ="http://172.16.10.14/mobile_lelang/create_lelang.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_form_lelang);
txtjudul = (EditText)findViewById(R.id.txtjudul);
txtharga = (EditText)findViewById(R.id.txtharga);
txtdate = (EditText)findViewById(R.id.txtdate);
btncreate = (Button)findViewById(R.id.btncreate);
btncreate.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.daftar, menu);
return true;
}
public void onClick(View view) {
// TODO Auto-generated method stub
if(view == btncreate){
new createJson().execute();
}
}
class createJson extends AsyncTask<String, String, String>{
Integer form_cek = 0;
#Override
protected void onPreExecute(){
super.onPreExecute();
if(txtjudul.getText().toString() == null)
{
alert.showAlertDialog(FormLelang.this, "Info", "Isi Judul", false);
//T_nama_d.focusSearch(0);
form_cek = 1;
}
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
if(txtjudul.getText().length() == 0)
{
form_cek = 1;
}
else if(txtharga.getText().length() == 0)
{
alert.showAlertDialog(FormLelang.this, "Info", "Harga Kosong", false);
form_cek = 1;
}
else if(txtdate.getText().length() == 0)
{
alert.showAlertDialog(FormLelang.this, "Info", "Isi Limit Date", false);
form_cek = 1;
}
if(form_cek == 0){
//Log.d("Form->",String.valueOf(form_cek));
ServiceHandler sh = new ServiceHandler();
List<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("judul", txtjudul.getText().toString()));
param.add(new BasicNameValuePair("harga", txtharga.getText().toString()));
param.add(new BasicNameValuePair("date", txtdate.getText().toString()));
//param.add(new BasicNameValuePair("jenis_kelamin", T_jeniskelamin_d.getSelectedItem().toString()));
String jsonstrr = sh.makeServiceCall(url, ServiceHandler.POST,param);
try {
JSONObject jsonobjj = new JSONObject(jsonstrr);
tag_besar = jsonobjj.getJSONArray("data");
for(int j = 0; j < tag_besar.length();j++){
JSONObject cc = tag_besar.getJSONObject(j);
success = cc.getInt("success");
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
protected void onPostExecute(String result){
if(form_cek == 0){
if(success == 1){
alert.showAlertDialog(FormLelang.this, "Info", "Data Berhasil Disimpan", true);
Intent setupIntent = new Intent(getApplicationContext(),MainActivity.class);
startActivityForResult(setupIntent, RESULT_OK);
finish();
}
else
{
alert.showAlertDialog(FormLelang.this, "Info", "Data Gagal Disimpan", false);
}
}
}
}
}
I have a Android app about Public Transportation, and I have a PHP script that connects to mySQL database. This is the main.java
package com.chera.trans;
import com.chera.trans.R;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
public class Main extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.traseu2:
Intent traseu2 = new Intent(this, Traseu2.class);
this.startActivity(traseu2);
break;
case R.id.traseu401:
Intent traseu401 = new Intent(this, Traseu401.class);
this.startActivity(traseu401);
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
}
And this is the code for Traseu2.java
package com.chera.trans;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.chera.trans.R;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class Traseu2 extends Activity {
private String jsonResult;
private String url = "http://transploiesti.tk/2.php";
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.traseu2);
listView = (ListView) findViewById(R.id.listView1);
accessWebService();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.traseu2:
Intent traseu2 = new Intent(this, Traseu2.class);
this.startActivity(traseu2);
break;
case R.id.traseu401:
Intent traseu401 = new Intent(this, Traseu401.class);
this.startActivity(traseu401);
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
ListDrwaer();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[] { url });
}
// build hash set for list view
public void ListDrwaer() {
List<Map<String, String>> employeeList = new ArrayList<Map<String, String>>();
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("traseudoi");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.optString("Statie");
String number = jsonChildNode.optString("Oraplecare");
String outPut = "Autobuzul pleaca din " + name + " la ora " + number;
employeeList.add(createEmployee("employees", outPut));
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
SimpleAdapter simpleAdapter = new SimpleAdapter(this, employeeList,
android.R.layout.simple_list_item_1,
new String[] { "employees" }, new int[] { android.R.id.text1 });
listView.setAdapter(simpleAdapter);
}
private HashMap<String, String> createEmployee(String name, String number) {
HashMap<String, String> employeeNameNo = new HashMap<String, String>();
employeeNameNo.put(name, number);
return employeeNameNo;
}
}
` Why I receive this error when I m running the app? Thanks!
HTML is not JSON, and it can not be parsed into JSONObjects. The top answer for org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject is pretty good at explaining this further.
I have a button that gets month and year from spinners then calls an Async task, which read json data. That part works fine But if I try and change the month and year then click the button again it does nothing. I have to press back to reload the page to click the button again to get different results.
Here is my code. Can any of you smart folks please help me.
package com.app.simplictyPortal;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.app.simplicityPortal.adapter.InvoiceAdapter;
import android.app.Fragment;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
public class InvoiceFragment extends Fragment {
public InvoiceFragment(){}
Button load;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_invoice, container, false);
ArrayList<String> years = new ArrayList<String>();
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
int currentMonth = Calendar.getInstance().get(Calendar.MONTH);
for (int i = 2013; i <= thisYear; i++)
{
years.add(Integer.toString(i));
}
//String tmonth = Integer.toString(currentMonth);
String tyear = Integer.toString(thisYear);
final Spinner year = (Spinner)rootView.findViewById(R.id.spinner1);
final Spinner month = (Spinner)rootView.findViewById(R.id.spinner2);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_item, years);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
year.setAdapter(adapter);
year.setSelection(adapter.getPosition(tyear));
ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(getActivity(),
R.array.month, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
month.setAdapter(adapter2);
month.setSelection(currentMonth);
load=(Button)rootView.findViewById(R.id.button1);
load.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String y = (String) year.getSelectedItem();
int im = month.getSelectedItemPosition();
String m = Integer.toString(im +1);
final GlobalClass globalVariable = (GlobalClass) getActivity().getApplicationContext();
final String Compid = globalVariable.getCompid();
new InvoiceAsyncTask().execute("http://dev-sql1:8080/api/invoice/getall/"+Compid+"?m="+m+"&y="+y);
}
});
return rootView;
}
public void invoice(JSONArray jArray) {
ListView lv = (ListView) getView().findViewById(R.id.listView1);
List<ListViewItem> items = new ArrayList<InvoiceFragment.ListViewItem>();
try {
for (int i = 0; i <jArray.length(); i++) {
final JSONObject json_data = jArray.getJSONObject(i);
items.add(new ListViewItem()
{{
Vendor= json_data.optString("CarrierName");
Bill = "$ " + json_data.optString("BillAmount");
Serviceacct = json_data.optString("ServiceAccountNumber");
Date = json_data.optString("ReceivedDate");
}});
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InvoiceAdapter adapter = new InvoiceAdapter(getActivity(), items);
lv.setAdapter(adapter);
// TODO Auto-generated method stub
}
public class ListViewItem
{
public String Vendor;
public String Bill;
public String Serviceacct;
public String Date;
} public static String GET(String url){
InputStream inputStream = null;
String result = "";
try {
// create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// make GET request to the given URL
HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
// receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return result;
}
private static 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;
}
public class InvoiceAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
return GET(urls[0]);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
try {
JSONArray jArray = new JSONArray(result);
invoice(jArray);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
How do you process results of your InvoiceAsyncTask? Do you implement a callback from your AsyncTask's onPostExecute() to the activity?
Maybe the sample below will help you.
First, implement AsyncTask class with callback interface:
public class ServerRequestAsyncTask extends AsyncTask<String, Void, ServerResponseDetails> {
public ServerRequestAsyncTask(Fragment fragment, ServerRequestDetails request) {
mFragment = fragment;
mRequest = request;
}
public interface OnServerRequestAsyncTaskCompletedListener {
void onServerRequestAsyncTaskCompleted(ServerResponseDetails response);
}
public void cancel() {
if (mHttpGet != null && !mHttpGet.isAborted()) mHttpGet.abort();
cancel(true);
}
And also add onPostExecute():
#Override
protected void onPostExecute(ServerResponseDetails response) {
if (mFragment != null) mFragment.onServerRequestAsyncTaskCompleted(response);
}
I call AsyncTask from Fragment, but you can use it with Activity instead.
Then, in your Activity you implement interface:
#Override
public void onServerRequestAsyncTaskCompleted(ServerResponseDetails response) {
// do what you need here, then 'finish' task by setting mServerRequest to null
mServerRequest = null;
}
And to execute AsyncTask:
protected ServerRequestAsyncTask mServerRequest = null;
public boolean isServerRequestRunning() {
return (mServerRequest != null);
}
public void cancelServerRequest() {
mServerRequest.cancel();
}
public void sendServerRequest(Fragment fragment, ServerRequestDetails request) {
if (Application.isNetworkAvailable()) {
if (!isServerRequestRunning()) {
mServerRequest = new ServerRequestAsyncTask(fragment, request);
mServerRequest.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
{params});
}
}
}
mServerRequest variable holds reference to currently executed task. You can call mServerRequest.cancel() if need to abort.
Thanks Everyone But I have figured it out. I needed to cancel the Async task in the post execute method.
#Override
protected void onPostExecute(String result) {
try {
JSONArray jArray = new JSONArray(result);
invoice(jArray);
cancel(true);
isCancelled();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Hey so I am not getting an error, but all my logs get initiated except for the one after HttpResponse not sure why, and on the server end I do not see any activity of a POST coming in...
here is my code:
package com.sfsfdsfds;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class wardrobe extends Activity{
//set variable for the fields
private EditText nameField;
private Spinner typeField;
private EditText colorField;
private Spinner seasonField;
private EditText sizeField;
private EditText quantityField;
private ImageView imageField;
private ProgressBar progressBarField;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.wardrobe);
ImageView user_photo = (ImageView) findViewById(R.id.user_photo);
//button for upload image
Button uploadImageButton = (Button) findViewById(R.id.uploadImageButton);
//button for posting details
Button postWardrobe = (Button) findViewById(R.id.postButton);
//Value of fields
nameField = (EditText) findViewById(R.id.nameFieldWardrobeScreen);
typeField = (Spinner) findViewById(R.id.typeFieldWardrobeScreen);
colorField = (EditText) findViewById(R.id.colorFieldWardrobeScreen);
seasonField = (Spinner) findViewById(R.id.seasonFieldWardrobeScreen);
sizeField = (EditText) findViewById(R.id.sizeFieldWardrobeScreen);
quantityField = (EditText) findViewById(R.id.quantityFieldWardrobeScreen);
imageField = (ImageView) findViewById(R.id.user_photo);
progressBarField = (ProgressBar) findViewById(R.id.progressBarWardrobe);
progressBarField.setVisibility(View.GONE);
//Creating spinner for select/options for type field
Spinner spinnerType = (Spinner) findViewById(R.id.typeFieldWardrobeScreen);
ArrayAdapter<CharSequence> adapterTypeArray = ArrayAdapter.createFromResource(this, R.array.type_array, android.R.layout.simple_spinner_item);
adapterTypeArray.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerType.setAdapter(adapterTypeArray);
//Creating spinner for select/options for season field
Spinner spinnerSeason = (Spinner) findViewById(R.id.seasonFieldWardrobeScreen);
ArrayAdapter<CharSequence> adapterSeasonArray = ArrayAdapter.createFromResource(this, R.array.season_array, android.R.layout.simple_spinner_item);
adapterSeasonArray.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerSeason.setAdapter(adapterSeasonArray);
uploadImageButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//below allows you to open the phones gallery
Image_Picker_Dialog();
}
});
postWardrobe.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//validate input and that something was entered
if(nameField.getText().toString().length()<1 || colorField.getText().toString().length()<1 || sizeField.getText().toString().length()<1 || quantityField.getText().toString().length()<1) {
//missing required info (null was this but lets see)
Toast.makeText(getApplicationContext(), "Please complete all sections!", Toast.LENGTH_LONG).show();
} else {
JSONObject dataWardrobe = new JSONObject();
try {
dataWardrobe.put("type", typeField.getSelectedItem().toString());
dataWardrobe.put("color", colorField.getText().toString());
dataWardrobe.put("season", seasonField.getSelectedItem().toString());
dataWardrobe.put("size", sizeField.getText().toString());
dataWardrobe.put("quantity", quantityField.getText().toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//make progress bar visible
progressBarField.setVisibility(View.VISIBLE);
//execute the post request
new dataSend().postData(dataWardrobe);
}
//below should send data over
}
});
}
// After the selection of image you will retun on the main activity with bitmap image
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Utility.GALLERY_PICTURE)
{
// data contains result
// Do some task
Image_Selecting_Task(data);
} else if (requestCode == Utility.CAMERA_PICTURE)
{
// Do some task
Image_Selecting_Task(data);
}
}
public void Image_Picker_Dialog()
{
AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(this);
myAlertDialog.setTitle("Pictures Option");
myAlertDialog.setMessage("Select Picture Mode");
myAlertDialog.setPositiveButton("Gallery", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface arg0, int arg1)
{
Utility.pictureActionIntent = new Intent(Intent.ACTION_GET_CONTENT, null);
Utility.pictureActionIntent.setType("image/*");
Utility.pictureActionIntent.putExtra("return-data", true);
startActivityForResult(Utility.pictureActionIntent, Utility.GALLERY_PICTURE);
}
});
myAlertDialog.setNegativeButton("Camera", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface arg0, int arg1)
{
Utility.pictureActionIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(Utility.pictureActionIntent, Utility.CAMERA_PICTURE);
}
});
myAlertDialog.show();
}
public void Image_Selecting_Task(Intent data)
{
ImageView user_photo = (ImageView) findViewById(R.id.user_photo);
try
{
Utility.uri = data.getData();
if (Utility.uri != null)
{
// User had pick an image.
Cursor cursor = getContentResolver().query(Utility.uri, new String[]
{ android.provider.MediaStore.Images.ImageColumns.DATA }, null, null, null);
cursor.moveToFirst();
// Link to the image
final String imageFilePath = cursor.getString(0);
//Assign string path to File
Utility.Default_DIR = new File(imageFilePath);
// Create new dir MY_IMAGES_DIR if not created and copy image into that dir and store that image path in valid_photo
Utility.Create_MY_IMAGES_DIR();
// Copy your image
Utility.copyFile(Utility.Default_DIR, Utility.MY_IMG_DIR);
// Get new image path and decode it
Bitmap b = Utility.decodeFile(Utility.Paste_Target_Location);
// use new copied path and use anywhere
String valid_photo = Utility.Paste_Target_Location.toString();
b = Bitmap.createScaledBitmap(b, 150, 150, true);
//set your selected image in image view
user_photo.setImageBitmap(b);
cursor.close();
} else
{
Toast toast = Toast.makeText(this, "Sorry!!! You haven't selecet any image.", Toast.LENGTH_LONG);
toast.show();
}
} catch (Exception e)
{
// you get this when you will not select any single image
Log.e("onActivityResult", "" + e);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
//Calling code for different selected menu options
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
//show settings activity screen (main preference activity file)
case R.id.wardrobe:
Intent intent = new Intent(wardrobe.this, wardrobe.class);
startActivity(intent);
//if index button clicked in menu sub-menu options
case R.id.matches:
Toast.makeText(this, "matches was clicked!", 5).show();
//if index button clicked in menu sub-menu options
case R.id.worn:
Toast.makeText(this, "worn was clicked!", 5).show();
default:
}
return super.onOptionsItemSelected(item);
}
private class dataSend extends AsyncTask<JSONObject, Integer, Double> {
protected Double doInBackground(JSONObject... params) {
// TODO Auto-generated method stub
postData(params[0]);
return null;
}
protected void onPostExecute(Double result) {
progressBarField.setVisibility(View.GONE);
Toast.makeText(wardrobe.this, "info sent", Toast.LENGTH_LONG).show();
}
protected void onProgressUpdate(Integer... progress) {
progressBarField.setProgress(progress[0]);
}
public void postData(JSONObject dataWardrobe) {
Log.v("posting data", "poooooost");
// Create a new HttpClient and Post Header
//int TIMEOUT_MILLISEC = 10000; // = 10 seconds
HttpParams httpParams = new BasicHttpParams();
//HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
//HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpClient httpclient = new DefaultHttpClient(httpParams);
HttpPost httppost = new HttpPost("http://127.0.0.1:3000/wardrobe");
Log.v("posteed", "posteed url");
try {
Log.v("trying data", "prep");
//add data
StringEntity se = new StringEntity( dataWardrobe.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(se);
Log.v("posteed", "posteed 11");
// execute http post request
HttpResponse response = httpclient.execute(httppost);
Log.v("posteed", "posteed 22");
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
}
Not sure what I am doing wrong, I tried various things and trying to look up different ways to go about doing this and none of them have worked... maybe it is something more simple than I see... the problem I think lies in the private class within this class.
I haven't read your code in great detail, but I suspect a strong contributor is this:
HttpPost httppost = new HttpPost("http://127.0.0.1:3000/wardrobe");
If you're using the emulator it's probably more likely you want to connect to "10.0.2.2". which is:
Special alias to your host loopback interface (i.e., 127.0.0.1 on your
development machine)
See here for more details on the emulator networking:
http://developer.android.com/tools/devices/emulator.html#emulatornetworking