I have questions about ListView and SharedPreference - java

I am a beginner developer who is studying Android.
The function I want to develop is "Save the data entered in EditText as JSON, save it as SharedPreference, and output it to ListView".
To save it as SharedPreference is OK, but, To output it to ListView is not working now.
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private ListView listView;
private Button save_btn;
private ArrayList<List> data = new ArrayList<List>();
ListAdapter adapter;
String title="";
String info="";
int img = R.drawable.man;
String jsondata;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
save_btn = (Button) findViewById(R.id.button1);
loadArrayList(getApplicationContext());
adapter = new ListAdapter(this, R.layout.row, data);
listView.setAdapter(adapter);
registerForContextMenu(listView);
save_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
View dlgview = View.inflate(MainActivity.this, R.layout.adds, null);
//adds.xml
final EditText et_title = (EditText) dlgview.findViewById(R.id.editText1);
final EditText et_info = (EditText) dlgview.findViewById(R.id.editText2);
ImageView img1 = (ImageView) dlgview.findViewById(R.id.imageView2);
AlertDialog.Builder dlg = new AlertDialog.Builder(MainActivity.this);
dlg.setTitle("ADD");
dlg.setView(dlgview);
dlg.setNegativeButton("Save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
try{
jsonObject.put("title", et_title.getText().toString());
jsonObject.put("info", et_info.getText().toString());
jsonObject.put("image",img);
jsonArray.put(jsonObject);
} catch (JSONException e){
e.printStackTrace();
}
jsondata = jsonArray.toString();
saveArrayList();
adapter.notifyDataSetChanged();
}
});
dlg.setPositiveButton("Cancel",null);
dlg.show();
}
});
}//End of onCreate
private void saveArrayList(){
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putString("jsonData", jsondata);
Log.i("moi","get Data test : " + "jsonData");
editor.apply();
}
private void loadArrayList(Context context){
SharedPreferences sharedPrefs2 = PreferenceManager.getDefaultSharedPreferences(context);
int size = sharedPrefs2.getInt("appreciation_size",0);
String strJson = sharedPrefs2.getString("jsonData", "fail");
Log.i("moi","get SharedPreferences test : " + strJson);
if (strJson != "fail")
{
try {
JSONArray response = new JSONArray(strJson);
for (int i=0; i<size; i++)
{
JSONObject jsonobject = response.getJSONObject(i);
title = jsonobject.getString("title");
Log.i("moi","title test : " + "title");
info = jsonobject.getString("info");
Log.i("moi","info test : " + "info");
data.add(new List(title, info, img));
}
adapter = new ListAdapter(getApplicationContext(), R.layout.row, data);
listView.setAdapter(adapter);
} catch (JSONException e){
e.printStackTrace();
}
}
}
}//End of class

Because you just called loadArrayList() once in onCreate(). That means your data in adapter just changes once.
you call adapter.notifyDataSetChanged() but this method doesnt callloadArrayList()`.
so try to save new json into data in onClick()

Try to remove your code:
adapter = new ListAdapter(this, R.layout.row, data);
listView.setAdapter(adapter);
in CreateView.
I think you set adapter listview double.
i hope that helps you.. thanks

Related

RecyclerView not loading

I have created a Recycler view that is supposed to be created when the activity is created. Currently, when I click a button on my MainActivity, an intent launches the ListActivity which has my recyclerview but it doesn't load. I have used toast message to confirm that each method is getting called, and that I am getting the correct data from the API. If I reset the activity using the restart activity option in Android Studio the Recycler shows up and functions correctly. I don't know what I'm doing wrong.
Here is my ListActivity:
private RecyclerView myrecyclerview;
private RecyclerView.Adapter myadapter;
private RecyclerView.LayoutManager mylayoutmanager;
static RequestQueue listqueue;
static final private String url = "https://swapi.dev/api/people/";
static ArrayList<RecyclerItem> list = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
getSupportActionBar().hide();
listqueue = Volley.newRequestQueue(this);
myrecyclerview = findViewById(R.id.characterlist);
myadapter = new MyAdapter(list, this);
myrecyclerview.setAdapter(myadapter);
myrecyclerview.setHasFixedSize(true);
mylayoutmanager = new LinearLayoutManager(getApplicationContext());
myrecyclerview.setLayoutManager(mylayoutmanager);
parseJsonData();
}
public void parseJsonData(){
JsonObjectRequest request = new JsonObjectRequest(
Request.Method.GET,
url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_SHORT).show();
try {
JSONArray jsonarray = response.getJSONArray("results");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String name = jsonobject.getString("name");
String height = jsonobject.getString("height");
String mass = jsonobject.getString("mass");
String eyecolor = jsonobject.getString("eye_color");
String birthyear = jsonobject.getString("birth_year");
//list.add(new RecyclerItem("darth vader", "200", "128", "1950", "red"));
list.add(new RecyclerItem(name, "Height: " + height, "Mass: " + mass, "Birth Year: " + birthyear, eyecolor));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
listqueue.add(request);
}
#Override
public void onCharacterClick(int position) {
String color = list.get(position).getEyecolor();
Toast.makeText(getApplicationContext(), color, Toast.LENGTH_SHORT).show();
}
} ```
Like I mentioned, once I reload the activity, it works correctly. But I want the recycler view to show when I navigate to the activity.
The problem is that the first time that the activity is create, list is empty and parseJsonData() is running on the background filling that list.
Once you reload the activiy, the list and adapter are filled therefore when you call
myadapter = new MyAdapter(list, this);
myrecyclerview.setAdapter(myadapter);
myrecyclerview.setHasFixedSize(true);
mylayoutmanager = new LinearLayoutManager(getApplicationContext());
myrecyclerview.setLayoutManager(mylayoutmanager);
the recycler view is show. Try to do this on your parseJsonData(); after the loop ends, then create the adapter and show the rv
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
....
}
myadapter = new MyAdapter(list, this);
....
myrecyclerview.setLayoutManager(mylayoutmanager);
I hope it help for u
Creat a List
private List< TipsList > tipsLists = new ArrayList<>();
SET UP RECYCLERVIEW LIKE THIS
RecyclerView tipsRv = findViewById(R.id.tips_rv);
TipsAdapter adapter = new TipsAdapter(tipsLists, this);
tipsRv.setAdapter(adapter);
tipsRv.setHasFixedSize(true);
tipsRv.setLayoutManager(new LinearLayoutManager(this));
getDATA
public void getWallis() {
String myJSONStr = method.loadJSON();
try {
JSONObject ROOT_OBJ = new JSONObject(myJSONStr);
JSONArray MAIN_ARRAY = ROOT_OBJ.getJSONArray("ff_api");
JSONObject TIPS_OBJ = MAIN_ARRAY.getJSONObject(3);
JSONArray TIPS_ARRAY = TIPS_OBJ.getJSONArray("Tips");
for (int i = 0; i < TIPS_ARRAY.length(); i++) {
TipsList tipsList = new TipsList();
JSONObject jsonObject = TIPS_ARRAY.getJSONObject(i);
tipsList.setId(jsonObject.getInt("id"));
tipsList.setTipsTitle(jsonObject.getString("tipsTitle"));
tipsList.setTipsDec(jsonObject.getString("tipsDec"));
tipsLists.add(tipsList);
}
} catch (JSONException e) {
e.printStackTrace();
}
}

How to parse data from one activity to another

Can anyone help me with this. I want to send data from edittext to another activity in the JSONMessage. I want to send to the IDDevice in my second activity.
Here is my code
It's my firstActivity
et = (EditText) findViewById(R.id.editText1);
bt = (Button) findViewById(R.id.bAdd);
lv = (ListView) findViewById(R.id.listView);
arrayList = new ArrayList<String>();
adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, arrayList);
lv.setAdapter(adapter);
onButtonClick();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String inputID = et.getText().toString();
Intent IDdevice = new Intent(MainActivity.this, ControlLed.class);
IDdevice.putExtra("ID", inputID);
startActivity(IDdevice);
}
});
}
And second activity
public void device1on(){
String topic = "server/esp001";
MqttMessage message = new MqttMessage();
message.setPayload("{\"idDevice\":\"esp001\",\"status\":\"0\",\"data\":\"100\",\"address\":\"1\",\"function\":\"1\",\"user\":\"admin\"}".getBytes());// I want to send data from first activity to the idDevice
try {
client.publish(topic, message);
} catch (MqttException e) {
e.printStackTrace();
}
}
In second activity, get id from Intent using getStringExtra method as mentioned below:
String id = getIntent().getStringExtra("ID");
And then set it to message object
JSONObject json = new JSONObject();
try {
json.put("idDevice", id);
json.put("status", "0");
json.put("data", "100");
json.put("address", "1");
json.put("function", "1");
json.put("user", "admin");
} catch (JSONException e) {
}
String payload = json.toString(); //"{\"idDevice\":\"value of id\",\"status\":\"0\",‌​\"data\":\"100\",\"a‌​ddress\":\"1\",\"fun‌​ction\":\"1\",\"user‌​\":\"admin\"}"
message.setPayload(payload.getBytes());
String getvallue;
Intent i=i.getIntent();
getVallue=i.getStringExtra("name");
Textview txt=(Textview)findviewbyid(R.id.txt);
txt.setText(getVallue);

How to save string sets to Shared Preferences

I have been able to save one entry to shared preferences and for it to display in a list view on another view but I am wanting to add multiple entries and them to display in the listview too. I thought I had the correct code but it doesn't see mto have changed anything. My intent is a favourites list, I take the entry data from one view and display it in another view.
SingleView Activity:
SharedPreferences.Editor fd;
SharedPreferences FeedPref;
private ArrayList<String> addArray = new ArrayList<>();
txt = (TextView) findViewById(R.id.name);
add = (Button) findViewById(R.id.btnAdd);
FeedPref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
fd = FeedPref.edit();
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String message = txt.getText().toString();
if (addArray.contains(message)) {
Toast.makeText((getBaseContext()), "Plant Already Added", Toast.LENGTH_LONG).show();
} else {
addArray.add(message);
FeedPref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
fd = FeedPref.edit();
fd.putInt("array_size", addArray.size());
for (int i = 0; i < addArray.size(); i++) {
fd.putString("Status_" + i, addArray.get(i));
}
fd.commit();
Toast.makeText((getBaseContext()), "Plant Added", Toast.LENGTH_LONG).show();
}
}
});
}
mygarden activity:
public class mygardenMain extends Activity {
//String[] presidents;
ListView listView;
//ArrayAdapter<String> adapter;
SharedPreferences FeedPref;
SharedPreferences.Editor fd;
//private ArrayList<String> addArray;
//public static final String PREFS = "examplePrefs";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mygarden_list);
listView = (ListView) findViewById(R.id.mygardenlist);
//addArray = new ArrayList<>();
FeedPref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
int size = FeedPref.getInt("array_size", 0);
for (int i = 0; i < size; i++) {
String mess = FeedPref.getString("Status_" + i, null);
String[] values = new String[]{mess};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, values);
listView.setAdapter(adapter);
}
}
Set abc = new HashSet<>();
abc.add("john");
abc.add("test");
abc.add("again");
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putStringSet("key",abc);
editor.commit();
SingleView Activity:
SharedPreferences.Editor fd;
SharedPreferences FeedPref;
private ArrayList<String> addArray = new ArrayList<>();
txt = (TextView) findViewById(R.id.name);
add = (Button) findViewById(R.id.btnAdd);
FeedPref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
fd = FeedPref.edit();
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String message = txt.getText().toString();
if (addArray.contains(message)) {
Toast.makeText((getBaseContext()), "Plant Already Added", Toast.LENGTH_LONG).show();
} else {
FeedPref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
fd = FeedPref.edit();
Gson gson = new Gson();
String jsonText = Prefs.getString("key", "");
if(!jsonText.equals(""))
{
String[] text = gson.fromJson(jsonText, String[].class); //EDIT: gso to gson
if(text.length>0)
{
//addArray = Arrays.asList(text);
//addArray = new ArrayList(addArray);
List<String> addArrayNew = Arrays.asList(text);
addArray = new ArrayList(addArrayNew);
}
}
addArray.add(message);
gson = new Gson();
jsonText = gson.toJson(addArray );
prefsEditor.putString("key", jsonText);
prefsEditor.commit();
}
});
}
mygarden activity:
public class mygardenMain extends Activity {
//String[] presidents;
ListView listView;
//ArrayAdapter<String> adapter;
SharedPreferences FeedPref;
SharedPreferences.Editor fd;
//private ArrayList<String> addArray;
//public static final String PREFS = "examplePrefs";
String jsonText;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mygarden_list);
listView = (ListView) findViewById(R.id.mygardenlist);
//addArray = new ArrayList<>();
FeedPref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
int size = FeedPref.getInt("array_size", 0);
Gson gson = new Gson();
jsonText = FeedPref.getString("key", "");
if(!jsonText.equals(""))
{
String[] values= gson.fromJson(jsonText, String[].class);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, values);
listView.setAdapter(adapter);
}
}

How to solve the error like java.lang.Throwable: setStateLocked?

I am developing an app. In it I'm using a listview. When I click on list item, it should go to next activity, i.e ProfileActivity2.java. It works fine, but in this ProfileActivty2 there is a button at the bottom and when I click on this button my app gets crashed and stopped in listview page. And shows the error java.lang.Throwable: setStateLocked in listview layout file i.e At setContentView. How do I solve this error?
//ProfileActivity2.java
public class ProfileActivity2 extends AppCompatActivity {
//Textview to show currently logged in user
private TextView textView;
private boolean loggedIn = false;
Button btn;
EditText edname,edaddress;
TextView tvsname, tvsprice;
NumberPicker numberPicker;
TextView textview1,textview2;
Integer temp;
String pname, paddress, email, sname, sprice;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile1);
//Initializing textview
textView = (TextView) findViewById(R.id.textView);
edname=(EditText)findViewById(R.id.ed_pname);
edaddress=(EditText)findViewById(R.id.ed_add);
tvsname=(TextView)findViewById(R.id.textView_name);
tvsprice=(TextView)findViewById(R.id.textView2_price);
btn=(Button)findViewById(R.id.button);
Intent i = getIntent();
// getting attached intent data
String name = i.getStringExtra("sname");
// displaying selected product name
tvsname.setText(name);
String price = i.getStringExtra("sprice");
// displaying selected product name
tvsprice.setText(price);
numberPicker = (NumberPicker)findViewById(R.id.numberpicker);
numberPicker.setMinValue(0);
numberPicker.setMaxValue(4);
final int foo = Integer.parseInt(price);
textview1 = (TextView)findViewById(R.id.textView1_amount);
textview2 = (TextView)findViewById(R.id.textView_seats);
// numberPicker.setValue(foo);
numberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
temp = newVal * foo;
// textview1.setText("Selected Amount : " + temp);
// textview2.setText("Selected Seats : " + newVal);
textview1.setText(String.valueOf(temp));
textview2.setText(String.valueOf(newVal));
// textview1.setText(temp);
// textview2.setText(newVal);
}
});
//Fetching email from shared preferences
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// submitForm();
// Intent intent = new Intent(ProfileActivity2.this, SpinnerActivity.class);
// startActivity(intent);
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
loggedIn = sharedPreferences.getBoolean(Config.LOGGEDIN_SHARED_PREF, false);
String email = sharedPreferences.getString(Config.EMAIL_SHARED_PREF, "Not Available");
textView.setText(email);
if(loggedIn){
submitForm();
Intent intent = new Intent(ProfileActivity2.this, SpinnerActivity.class);
startActivity(intent);
}
}
});
}
private void submitForm() {
// Submit your form here. your form is valid
//Toast.makeText(this, "Submitting form...", Toast.LENGTH_LONG).show();
String pname = edname.getText().toString();
String paddress = edaddress.getText().toString();
String sname = textview1.getText().toString();
// String sname= String.valueOf(textview1.getText().toString());
String sprice= textview2.getText().toString();
// String sprice= String.valueOf(textview2.getText().toString());
String email= textView.getText().toString();
Toast.makeText(this, "Signing up...", Toast.LENGTH_SHORT).show();
new SignupActivity(this).execute(pname,paddress,sname,sprice,email);
}
}
//SignupActivity
public class SignupActivity extends AsyncTask<String, Void, String> {
private Context context;
Boolean error, success;
public SignupActivity(Context context) {
this.context = context;
}
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... arg0) {
String pname = arg0[0];
String paddress = arg0[1];
String sname = arg0[2];
String sprice = arg0[3];
String email = arg0[4];
String link;
String data;
BufferedReader bufferedReader;
String result;
try {
data = "?pname=" + URLEncoder.encode(pname, "UTF-8");
data += "&paddress=" + URLEncoder.encode(paddress, "UTF-8");
data += "&sname=" + URLEncoder.encode(sname, "UTF-8");
data += "&sprice=" + URLEncoder.encode(sprice, "UTF-8");
data += "&email=" + URLEncoder.encode(email, "UTF-8");
link = "http://example.in/Spinner/update.php" + data;
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
result = bufferedReader.readLine();
return result;
} catch (Exception e) {
// return new String("Exception: " + e.getMessage());
// return null;
}
return null;
}
#Override
protected void onPostExecute(String result) {
String jsonStr = result;
Log.e("TAG", jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String query_result = jsonObj.getString("query_result");
if (query_result.equals("SUCCESS")) {
Toast.makeText(context, "Success! Your are Now MangoAir User.", Toast.LENGTH_LONG).show();
} else if (query_result.equals("FAILURE")) {
Toast.makeText(context, "Looks Like you already have Account with US.", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
// Toast.makeText(context, "Error parsing JSON Please data Fill all the records.", Toast.LENGTH_SHORT).show();
// Toast.makeText(context, "Please LogIn", Toast.LENGTH_SHORT).show();
Toast.makeText(context, "Please Login", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(context, "Grrr! Check your Internet Connection.", Toast.LENGTH_SHORT).show();
}
}
}
//List_Search
public class List_Search extends AppCompatActivity {
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String SNAME = "sname";
static String SPRICE = "sprice";
Context ctx = this;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.list_search);
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(List_Search.this);
// Set progressdialog title
mProgressDialog.setTitle("Android JSON Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://example.in/MangoAir_User/mangoair_reg/ListView1.php");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("result");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("sname", jsonobject.getString("sname"));
map.put("sprice", jsonobject.getString("sprice"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listView_search);
// Pass the results into ListViewAdapter.java
// adapter = new ListViewAdapter(List_Search.this, arraylist);
adapter = new ListViewAdapter(ctx, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
//ListViewAdapter
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
private boolean loggedIn = false;
ArrayList<HashMap<String, String>> data;
HashMap<String, String> resultp = new HashMap<String, String>();
public ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView name,price;
Button btn;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.search_item, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
name = (TextView) itemView.findViewById(R.id.textView8_sellernm);
// Capture position and set results to the TextViews
name.setText(resultp.get(List_Search.SNAME));
price = (TextView) itemView.findViewById(R.id.textView19_bprice);
// Capture position and set results to the TextViews
price.setText(resultp.get(List_Search.SPRICE));
btn=(Button)itemView.findViewById(R.id.button3_book);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
resultp = data.get(position);
Intent intent = new Intent(context, ProfileActivity2.class);
// Pass all data rank
intent.putExtra("sname", resultp.get(List_Search.SNAME));
intent.putExtra("sprice", resultp.get(List_Search.SPRICE));
context.startActivity(intent);
}
});
return itemView;
}
}
context.startActivity(intent);
I think the error is at this line inside btn.setOnClickListener of getview block just use startActivity(intent);

ANDROID: Filter Listview data from PHP JSON using LAZYLIST

Im currently developing a mobile ordering app, and im using listview from https://github.com/thest1/LazyList for the summary of my orders but my problem is that all data of ORDERS from my database (Mysql) is showing.
I want to show only the orders per Customer ID
heres the sample image
-- > http://postimg.org/image/dnayd433x/
OrderSum.java
**OrderSum.java
public class OrderSum extends Activity{
ListView list;
TextView id; //// ver - id
TextView name; //// name - name
TextView quan; //// api - desc
TextView price; //// price
TextView order_num; //// price
TextView cust_num; //// price
ImageView image;
TextView items;
TextView empty;
TextView home_ornum;
TextView cust_name;
ImageButton addOrder;
ImageButton proceed;
DigitalClock time;
TextView os;
TextView o_total;
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
LvOrderSumAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String ID = "id";
static String NAME = "ord_name";
static String PRICE = "ord_price";
static String QTY = "ord_qty";
static String CUSTID = "customer_id";
static String ORDER = "ord_num";
static String PXQ = "price_x_quan";
static String IMAGE = "image";
static String OR = "text_ordernumber";
static String ON = "text_name";
static String TP = "t_price";
///////////////////////
#SuppressLint({ "SimpleDateFormat", "NewApi" })
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.order_summary);
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
/**Unique ID / Customer Id***/
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
/**
* Hashmap to load data from the Sqlite database
**/
HashMap user = new HashMap();
user = db.getUserDetails();
final TextView unique_id = (TextView) findViewById(R.id.o_custnum);
unique_id.setText((CharSequence) user.get("uid"));
/**END**/
/** DATE VIEW***/
TextView h_date = (TextView) findViewById(R.id.o_date);
Calendar c = Calendar.getInstance();
SimpleDateFormat format1;
format1 = new SimpleDateFormat("MMMM dd,yyyy");
// format2 = new SimpleDateFormat("dd-MM-yyyy-HH-mm-ss");
h_date.setText(format1.format(c.getTime()) );
/** END DATE VIEW***/
cust_name = (TextView) findViewById(R.id.DisplaycustName);
home_ornum = (TextView) findViewById(R.id.Displayordernum);
time = (DigitalClock) findViewById(R.id.o_time);
Intent myIntent = getIntent();
home_ornum.setText(myIntent.getStringExtra("text_ordernumber")); //order number is the TextView
cust_name.setText(myIntent.getStringExtra("text_name")); //tv is the TextView
items= (TextView) findViewById(R.id.DisplayTotalItems);
/***************Custom Font***/
Typeface myCustomFont = Typeface.createFromAsset(getAssets(), "fonts/MavenPro.otf");
cust_name.setTypeface(myCustomFont);
home_ornum.setTypeface(myCustomFont);
time.setTypeface(myCustomFont);
h_date.setTypeface(myCustomFont);
/***************Custom Font**************/
addOrder = (ImageButton) findViewById(R.id.btn_add);
addOrder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(OrderSum.this,
Categories.class);
startActivity(myIntent);
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left);
}
});
/***************************PROCEED BUTTON***************************/
proceed = (ImageButton) findViewById(R.id.btn_proceed);
proceed.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(OrderSum.this,
OrderInformation.class);
startActivity(myIntent);
// uniq id , order no , date , name
// final TextView d_date = (TextView) findViewById(R.id.o_date);
Intent ord_in = new Intent ( OrderSum.this, OrderInformation.class );
ord_in.putExtra ( "text_order", home_ornum.getText().toString() );
// ord_in.putExtra ( "text_date", d_date.getText().toString() );
ord_in.putExtra ( "text_custName", cust_name.getText().toString() );
ord_in.putExtra ( "text_items", items.getText().toString() );
startActivity(ord_in);
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left);
}
});
/***************************PROCEED BUTTON***************************/
/**for the ROOF2**/
final ActionBar actionBar = getActionBar();
BitmapDrawable background = new BitmapDrawable
(BitmapFactory.decodeResource(getResources(), R.drawable.roof2));
///background.setTileModeX(android.graphics.Shader.TileMode.REPEAT);
actionBar.setBackgroundDrawable(background);
/**end for the ROOF2**/
} /// end of OnCreate
#Override
public void onBackPressed() {
super.onBackPressed();
/*Intent myIntent = new Intent(OrderSum.this,
Home.class);
startActivity(myIntent);*/
TextView on = (TextView) findViewById(R.id.Displayordernum);
Intent home_in = new Intent ( OrderSum.this, Home.class );
home_in.putExtra ( "text_ordernumber", on.getText().toString() );
startActivity(home_in);
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left);
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(OrderSum.this);
// Set progressdialog title
mProgressDialog.setTitle("Your orders");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
TextView custname = (TextView) findViewById(R.id.DisplaycustName);
TextView homeornum = (TextView) findViewById(R.id.Displayordernum);
Intent home_in = getIntent();
homeornum.setText(home_in.getStringExtra("text_ordernumber")); //tv is the TextView
custname.setText(home_in.getStringExtra("text_name")); //name is the TextView
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
JSONObject jsonobject = JSONfunctions.getJSONfromURL("http://192.168.43.52/MMOS/api/ordershow.php") ;
// jsonobject = JSONfunctions.getJSONfromURL( //192.168.43.52 /// 10.0.2.2
// ordershow, "GET", params);
//jsonobject = JSONfunctions.getJSONfromURL(,)
try {
// Locate the array name in JSON==
jsonarray = jsonobject.getJSONArray("orders");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
/* from db orders = id,ord_name,ord_desc,
ord_price,ord_qty,customer_id,ord_num,price_x_quan , image jsonobjecy = from db*/
map.put("id", jsonobject.getString("id"));
map.put("ord_name", jsonobject.getString("ord_name"));
map.put("ord_price", jsonobject.getString("ord_price"));
map.put("ord_qty", jsonobject.getString("ord_qty"));
map.put("customer_id", jsonobject.getString("customer_id"));
map.put("ord_num", jsonobject.getString("ord_num"));
map.put("price_x_quan", jsonobject.getString("price_x_quan"));
map.put("image", jsonobject.getString("image"));
map.put("text_ordernumber",home_in.getStringExtra("text_ordernumber"));
map.put("text_name",home_in.getStringExtra("text_name"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listOrderSummary);
// Pass the results into ListViewAdapter.java
adapter = new LvOrderSumAdapter(OrderSum.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
listview.getAdapter().getCount();
String count = ""+listview.getAdapter().getCount();
items.setText(count);
// Close the progressdialog
mProgressDialog.dismiss();
}
} **
and for the JSONFUNCTION
** public class JSONfunctions {
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// Convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
and the PHP CODE
<?php
mysql_connect('localhost','root','')or die ('No Connection');
mysql_select_db('dbmoms');
//$o_od = $_GET['text_ordernumber'];
$sql ="SELECT * FROM orders"; // WHERE ord_num ='$o_od' "; //WHERE ord_num = '$ordnum'
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)){
$arr['orders'][]= $row;
}
$json = json_encode($arr);
$json_encoded_string = json_encode($arr);
$json_encoded_string = str_replace("\\/", '/', $json_encoded_string);
echo $json_encoded_string;
?>
I hope that you can help me :)
thanks in advance. :)

Categories

Resources