我正在尝试从服务器检索数据并将其显示在listview中。但是当我编译它时它不起作用,列表甚至没有显示在活动中。
Mylist.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="@dimen/fab_margin"
android:orientation="vertical" >
<AbsoluteLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/edItem"
android:layout_width="180dp"
android:layout_marginTop="10dp"
android:layout_height="40dp"
android:layout_marginLeft="10dp"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="180dp"
android:orientation="horizontal">
<TextView
android:id="@+id/edUnit"
android:layout_width="100dp"
android:layout_marginTop="80dp"
android:layout_height="40dp"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp"/>
<TextView
android:id="@+id/edPrice"
android:layout_width="100dp"
android:layout_marginTop="80dp"
android:layout_height="40dp"
android:layout_marginLeft="10dp"/>
<TextView
android:id="@+id/edDisc"
android:layout_width="100dp"
android:layout_height="40dp"
android:layout_marginRight="10dp"
android:layout_marginTop="80dp"
android:layout_marginLeft="10dp"/>
</LinearLayout>
</AbsoluteLayout>
</LinearLayout>
Content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.example.user.merchant.MainActivity"
tools:showIn="@layout/app_bar_main">
<ListView
android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:dividerHeight="10dp">
</ListView>
<SearchView
android:id="@+id/search_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</SearchView>
</RelativeLayout>
AppController.java
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
// private ImageLoader mImageLoader;
private static AppController mInstance;
@Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
// set the default tag if tag is empty
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
CustomListAdapter.java
public class CustomListAdapter extends BaseAdapter implements Filterable {
private Activity activity;
CustomFilter filter;
private LayoutInflater inflater;
private List<InventoryModel> InventoryModelItems;
private List<InventoryModel> filterList;
public CustomListAdapter(Activity activity, List<InventoryModel> InventoryModelItems) {
this.activity = activity;
this.InventoryModelItems = InventoryModelItems;
this.filterList=InventoryModelItems;
}
@Override
public int getCount() {
return InventoryModelItems.size();
}
@Override
public Object getItem(int location) {
return InventoryModelItems.get(location);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.mylist, null);
TextView ItemName = (TextView) convertView.findViewById(R.id.edItem);
TextView Unit = (TextView) convertView.findViewById(R.id.edUnit);
TextView Price = (TextView) convertView.findViewById(R.id.edPrice);
TextView Discount = (TextView) convertView.findViewById(R.id.edDisc);
// getting InventoryModel data for the row
InventoryModel m = InventoryModelItems.get(position);
// thumbnail image
// title
ItemName.setText(m.getItemName());
// rating
Unit.setText("Unit: " + (m.getUnit()));
// release year
Price.setText("Rs: " + String.valueOf(m.getPrice()));
Discount.setText("Discount: " + String.valueOf(m.getUnit()));
return convertView;
}
@Override
public Filter getFilter() {
if(filter==null)
{
filter=new CustomFilter();
}
return filter;
}
class CustomFilter extends Filter
{
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results=new FilterResults();
if(constraint != null&&constraint.length()>0)
{
constraint=constraint.toString().toUpperCase();
ArrayList<InventoryModel> filters=new ArrayList<InventoryModel>();
for(int i=0;i<filterList.size();i++)
{
if(filterList.get(i).getItemName().toUpperCase().contains(constraint))
{
InventoryModel p= new InventoryModel(filterList.get(i).getItemName(),filterList.get(i).getUnit(),filterList.get(i).getPrice(),filterList.get(i).getDiscount());
filters.add(p);
}
}
results.count=filters.size();
results.values=filters;
}
else
{
results.count=filterList.size();
results.values=filterList;
}
return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
InventoryModelItems=(List<InventoryModel>) results.values;
notifyDataSetChanged();
}
}
}
mainactivity.java
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private static final String TAG = MainActivity.class.getSimpleName();
private static final String url = "url";
private ProgressDialog pDialog;
private List<InventoryModel> InventoryModelList = new ArrayList<InventoryModel>();
private ListView listView;
private CustomListAdapter adapter;
public TextView test;
SearchView inputSearch;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView=(ListView)findViewById(R.id.list);
adapter = new CustomListAdapter(this, InventoryModelList);
listView.setAdapter(adapter);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//toolbar.setLogo(R.drawable.ic_menu_slideshow);
//toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_menu_slideshow));
// test=(TextView)findViewById(R.id.listtest);
setSupportActionBar(toolbar);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// changing action bar color
assert getSupportActionBar() != null;
getSupportActionBar().setBackgroundDrawable(
new ColorDrawable(Color.parseColor("#1b1b1b")));
JsonArrayRequest InventoryModelReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
// test.setText(response);
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
InventoryModel InventoryModel = new InventoryModel();
InventoryModel.setItemName(obj.getString("Item_Name"));
InventoryModel.setUnit(obj.getString("Unit"));
InventoryModel.setPrice(((Number) obj.get("Price"))
.floatValue());
InventoryModel.setDiscount(((Number) obj.get("Discount")).floatValue());
// adding InventoryModel to InventoryModels array
InventoryModelList.add(InventoryModel);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
AppController.getInstance().addToRequestQueue(InventoryModelReq);
/* toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intenthome = new Intent(MainActivity.this, MainActivity.class);
startActivity(intenthome);
}
});*/
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intentfloat = new Intent(MainActivity.this, ItemAdd.class);
startActivity(intentfloat);
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
//toggle.setHomeAsUpIndicator(R.drawable.ic_menu_slideshow);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@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;
}
@Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
@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();
//noinspection SimplifiableIfStatement
if(id == R.id.account) {
Intent intentaccount = new Intent(MainActivity.this, account.class);
startActivity(intentaccount);
}
if (id == R.id.action_settings) {
return true;
}
if(id==R.id.action_notify) {
Intent intentNotify = new Intent(MainActivity.this, Notification.class);
startActivity(intentNotify);
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_processing) {
// Handle the camera action
Intent intentProcessing = new Intent(MainActivity.this, ProcessingItem.class);
startActivity(intentProcessing);
} else if (id == R.id.nav_processed) {
Intent intentProcessed = new Intent(MainActivity.this, ProcessedItem.class);
startActivity(intentProcessed);
} else if (id == R.id.nav_Aborted) {
Intent intentAborted = new Intent(MainActivity.this, AbortedIem.class);
startActivity(intentAborted);
} else if (id == R.id.nav_delivery) {
Intent intentDelivered = new Intent(MainActivity.this, DeliveredItem.class);
startActivity(intentDelivered);
}
else if (id == R.id.logout)
{
// private void logout(){
//Creating an alert dialog to confirm logout
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("Are you sure you want to logout?");
alertDialogBuilder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
//Getting out sharedpreferences
SharedPreferences preferences = getSharedPreferences(config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
//Getting editor
SharedPreferences.Editor editor = preferences.edit();
//Puting the value false for loggedin
editor.putBoolean(config.LOGGEDIN_SHARED_PREF, false);
//Putting blank value to email
editor.putString(config.EMAIL_SHARED_PREF, "");
//Saving the sharedpreferences
editor.commit();
//Starting login activity
Intent intent = new Intent(MainActivity.this, LoginActivityMerchant.class);
startActivity(intent);
}
});
alertDialogBuilder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
}
});
//Showing the alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}