I am trying to search a JSON data fetched from a URL, but whenever the user types a search string the application crashes. How do I fix it?
Here is my code:
MainActivity.java
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
private EditText filterText;
private ArrayAdapter<String> listAdapter;
// URL to get contacts JSON
private static String url = "http://210.213.86.195:14344/inventory/getallitemname";
ArrayList<HashMap<String, String>> itemList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
filterText = (EditText)findViewById(R.id.editText);
itemList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list_item);
new GetItems().execute();
filterText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
MainActivity.this.listAdapter.getFilter().filter(s);
}
#Override
public void afterTextChanged(Editable s) {
}
}
);
}
/**
* Async task class to get json by making HTTP call
*/
private class GetItems extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray items = jsonObj.getJSONArray("Data");
// looping through All Contacts
for (int i = 0; i < items.length(); i++) {
JSONObject c = items.getJSONObject(i);
String ItemCode = c.getString("ItemCode");
String ItemName = c.getString("ItemName");
// tmp hash map for single item
HashMap<String, String> item = new HashMap<>();
// adding each child node to HashMap key => value
item.put("ItemCode", ItemCode);
item.put("ItemName", ItemName);
// adding item to item list
itemList.add(item);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, itemList,
R.layout.list_item, new String[]{"ItemCode", "ItemName"}, new int[]{R.id.ItemCode,
R.id.ItemName});
lv.setAdapter(adapter);
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.jsonparser.MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/editText"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<ListView
android:id="#+id/list_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:layout_marginTop="10dp"
android:layout_below="#+id/editText"
android:layout_alignLeft="#+id/editText"
android:layout_alignStart="#+id/editText" />
</RelativeLayout>
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="#dimen/activity_horizontal_margin">
<TextView
android:id="#+id/ItemName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:paddingTop="6dip"
android:textColor="#color/colorPrimaryDark"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="#+id/ItemCode"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:textColor="#color/colorAccent" />
</LinearLayout>
you have not initalized it anywhere in code:-
MainActivity.this.listAdapter
so default is null,in postExecute you are using local adapter variable.
Put
adapter = new ArrayAdapter<String>(this,
R.layout.list_view_rows, R.id.listview, ListofStringYouWantToDisplay);
below
lv = (ListView) findViewById(R.id.list_item);
hear - ListofStringYouWantToDisplay is String[] or ArrayList you want to display
Your problem is you not initializing adapter before use
Related
I am working on android application and I am facing one problem. When I run my app then nothing showing in recycle view but when i check application in debug mode then data successfully showing in recycle view. I have checked my web service working fine and successfully giving data. How can i achieve this ?
ManageQuestionActivity,java
public class ManageQuestionActivity extends AppCompatActivity implements RecyclerView.OnScrollChangeListener{
private static final String TAG = MainActivity.class.getSimpleName();
private RecyclerView listView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
private QuestionsListAdapter listAdapter;
private List<QuestionsItem> timeLineItems;
private int requestCount = 1;
private ProgressDialog pDialog;
public static String id, message, token, encodedString;
int pageCount, totalPages;
SQLiteHandler db;
SessionManager session;
ConnectionDetector cd;
EditText edtSearch;
Boolean isInternetPresent = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manage_question);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
listView = (RecyclerView) findViewById(R.id.list);
edtSearch = (EditText) findViewById(R.id.edtSearch);
listView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
listView.setLayoutManager(layoutManager);
//Adding an scroll change listener to recyclerview
listView.setOnScrollChangeListener(this);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
cd = new ConnectionDetector(this);
isInternetPresent = cd.isConnectingToInternet();
db = new SQLiteHandler(this);
// session manager
session = new SessionManager(this);
// Fetching user details from sqlite
HashMap<String, String> user = db.getUserDetails();
id = user.get("id");
token = user.get("token");
getData();
timeLineItems = new ArrayList<>();
adapter = new QuestionsListAdapter(timeLineItems, this);
listView.setAdapter(adapter);
}
public void getTimeLineData(final String token, final String page) {
String tag_string_req = "req_register";
// making fresh volley request and getting json
StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.questions, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
VolleyLog.d(TAG, "Response: " + response.toString());
if (response != null) {
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("status");
String message = jObj.getString("message");
if (error) {
totalPages = jObj.getInt("totalPages");
pageCount = jObj.getInt("page");
int limit = jObj.getInt("limit");
parseJsonFeed(response);
}
} catch (Exception e) {
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("my_token", token);
params.put("page", page);
params.put("limit", "20");
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void parseJsonFeed(String response) {
try {
JSONObject jsonObj = new JSONObject(response);
JSONArray feedArray = jsonObj.getJSONArray("data");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
QuestionsItem item = new QuestionsItem();
item.setId(feedObj.getInt("id"));
item.setQuestion(feedObj.getString("question"));
String options = feedObj.getString("multi_ans_option");
String[] parts = options.split("\\|");
String part1 = parts[0];
String part2 = parts[1];
String part3 = parts[2];
String part4 = parts[3];
item.setAnsOne(part1);
item.setAnsTwo(part2);
item.setAnsThree(part3);
item.setAnsFour(part4);
item.setAnswer(feedObj.getString("answer"));
timeLineItems.add(item);
}
// notify data changes to list adapater
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
private void getData() {
//Adding the method to the queue by calling the method getDataFromServer
getTimeLineData(token, String.valueOf(requestCount));
//Incrementing the request counter
requestCount++;
}
//This method would check that the recyclerview scroll has reached the bottom or not
private boolean isLastItemDisplaying(RecyclerView recyclerView) {
if (recyclerView.getAdapter().getItemCount() != 0) {
int lastVisibleItemPosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastCompletelyVisibleItemPosition();
if (lastVisibleItemPosition != RecyclerView.NO_POSITION && lastVisibleItemPosition == recyclerView.getAdapter().getItemCount() - 1)
return true;
}
return false;
}
#Override
public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
//Ifscrolled at last then
if (isLastItemDisplaying(listView)) {
//Calling the method getdata again
getData();
}
}
}
activity_manage_question.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#null" />
</LinearLayout>
QuestionsItem.java
public class QuestionsItem {
private int id;
private String question, ansOne, ansTwo, ansThree, ansFour, answer;
public QuestionsItem() {
}
public QuestionsItem(int id, String question, String ansOne, String ansTwo, String ansThree, String ansFour, String answer) {
super();
this.id = id;
this.question = question;
this.ansOne = ansOne;
this.ansTwo = ansTwo;
this.ansThree = ansThree;
this.ansFour = ansFour;
this.answer = answer;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getAnsOne() {
return ansOne;
}
public void setAnsOne(String ansOne) {
this.ansOne = ansOne;
}
public String getAnsTwo() {
return ansTwo;
}
public void setAnsTwo(String ansTwo) {
this.ansTwo = ansTwo;
}
public String getAnsThree() {
return ansThree;
}
public void setAnsThree(String ansThree) {
this.ansThree = ansThree;
}
public String getAnsFour() {
return ansFour;
}
public void setAnsFour(String ansFour) {
this.ansFour = ansFour;
}
public String getAnswer() {
return answer;
}
public void setAnswer(String answer) {
this.answer = answer;
}
}
QuestionsListAdapter.java
public class QuestionsListAdapter extends RecyclerView.Adapter<QuestionsListAdapter.ViewHolder> {
private List<QuestionsItem> timeLineItems;
String message, storyId, token, ide;
private Context context;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
ConnectionDetector cd;
Boolean isInternetPresent = false;
private ProgressDialog pDialog;
private SessionManager session;
private SQLiteHandler db;
int newPosition;
public QuestionsListAdapter(List<QuestionsItem> timeLineItems, Context context) {
super();
this.context = context;
this.timeLineItems = timeLineItems;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.questios_item, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
pDialog = new ProgressDialog(context);
pDialog.setCancelable(false);
db = new SQLiteHandler(context);
// session manager
session = new SessionManager(context);
// Fetching user details from sqlite
HashMap<String, String> user = db.getUserDetails();
token = user.get("token");
//Getting the particular item from the list
QuestionsItem item = timeLineItems.get(position);
holder.txtQues.setText(item.getQuestion());
holder.txtAnsOne.setText(item.getAnsOne());
holder.txtAnsTwo.setText(item.getAnsTwo());
holder.txtAnsThree.setText(item.getAnsThree());
holder.txtAnsFour.setText(item.getAnsFour());
holder.txtAns.setText(item.getAnswer());
holder.btnEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final QuestionsItem m = timeLineItems.get(position);
String ide = String.valueOf(m.getId());
String ques = String.valueOf(m.getQuestion());
String Option1 = String.valueOf(m.getAnsOne());
String Option2 = String.valueOf(m.getAnsTwo());
String Option3 = String.valueOf(m.getAnsThree());
String Option4 = String.valueOf(m.getAnsFour());
String answer = String.valueOf(m.getAnswer());
Intent intent = new Intent(context, UpdateQuestionActivity.class);
intent.putExtra("id", ide);
intent.putExtra("ques", ques);
intent.putExtra("option1", Option1);
intent.putExtra("option2", Option2);
intent.putExtra("option3", Option3);
intent.putExtra("option4", Option4);
intent.putExtra("answer", answer);
context.startActivity(intent);
}
});
holder.btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final QuestionsItem m = timeLineItems.get(position);
newPosition = holder.getAdapterPosition();
ide = String.valueOf(m.getId());
alertBox();
}
});
}
#Override
public int getItemCount() {
return timeLineItems.size();
}
#Override
public int getItemViewType(int position)
{
return position;
}
class ViewHolder extends RecyclerView.ViewHolder{
TextView txtQues, txtAnsOne, txtAnsTwo, txtAnsThree, txtAnsFour, txtAns, btnEdit, btnDelete;
//Initializing Views
public ViewHolder(View itemView) {
super(itemView);
txtQues = (TextView) itemView.findViewById(R.id.txtQues);
txtAnsOne = (TextView) itemView.findViewById(R.id.txtAnsOne);
txtAnsTwo = (TextView) itemView.findViewById(R.id.txtAnsTwo);
txtAnsThree = (TextView) itemView.findViewById(R.id.txtAnsThree);
txtAnsFour = (TextView) itemView.findViewById(R.id.txtAnsFour);
txtAns = (TextView) itemView.findViewById(R.id.txtAns);
btnEdit = (TextView) itemView.findViewById(R.id.btnEdit);
btnDelete = (TextView) itemView.findViewById(R.id.btnDelete);
}
}
public void alertBox(){
AlertDialog.Builder builder = new AlertDialog.Builder(context);
//Uncomment the below code to Set the message and title from the strings.xml file
//builder.setMessage(R.string.dialog_message) .setTitle(R.string.dialog_title);
//Setting message manually and performing action on button click
builder.setMessage("Do you want to delete question ?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Check for empty data in the form
cd = new ConnectionDetector(context);
isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent){
DeleteQuestion(token, ide);
}else {
final SweetAlertDialog alert = new SweetAlertDialog(context, SweetAlertDialog.WARNING_TYPE);
alert.setTitleText("No Internet");
alert.setContentText("No connectivity. Please check your internet.");
alert.show();
}
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Action for 'NO' Button
dialog.cancel();
}
});
//Creating dialog box
AlertDialog alert = builder.create();
//Setting the title manually
alert.setTitle("Question");
alert.show();
}
private void DeleteQuestion(final String token, final String qid) {
// Tag used to cancel the request
String tag_string_req = "req_register";
pDialog.setMessage("Please wait ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.updateQues, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("status");
if (error) {
String errorMsg = jObj.getString("message");
Toast.makeText(context, errorMsg, Toast.LENGTH_SHORT).show();
timeLineItems.remove(newPosition);
notifyItemRemoved(newPosition);
notifyItemRangeChanged(newPosition, timeLineItems.size());
} else {
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("message");
Toast.makeText(context, errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "Oops something went wrong...", Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("my_token", token);
params.put("qid", qid);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
questios_item.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="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5dp"
android:background="#color/white">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Question : "
android:textColor="#000000"
android:textSize="15sp" />
<TextView
android:id="#+id/txtQues"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="#dimen/feed_item_profile_name"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 1 : "
android:textColor="#000000"
android:textSize="15sp" />
<TextView
android:id="#+id/txtAnsOne"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="#dimen/feed_item_profile_name"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 2 : "
android:textColor="#000000"
android:textSize="15sp" />
<TextView
android:id="#+id/txtAnsTwo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="#dimen/feed_item_profile_name"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 3 : "
android:textColor="#000000"
android:textSize="15sp" />
<TextView
android:id="#+id/txtAnsThree"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="#dimen/feed_item_profile_name"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 4 : "
android:textColor="#000000"
android:textSize="15sp" />
<TextView
android:id="#+id/txtAnsFour"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="#dimen/feed_item_profile_name"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Answer : "
android:textColor="#000000"
android:textSize="15sp" />
<TextView
android:id="#+id/txtAns"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="#dimen/feed_item_profile_name"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="2">
<TextView android:id="#+id/btnEdit"
android:layout_width="0dp"
android:layout_height="30dp"
android:text="Edit"
android:background="#drawable/rounded_square_comment"
android:gravity="center"
android:textColor="#000000"
android:layout_weight="1"
android:textSize="15sp" />
<TextView
android:id="#+id/btnDelete"
android:layout_width="0dp"
android:layout_height="30dp"
android:text="Delete"
android:background="#drawable/rounded_square_comment"
android:gravity="center"
android:textColor="#000000"
android:layout_weight="1"
android:textSize="15sp" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
listView.setAdapter should not be here cut
timeLineItems = new ArrayList<>();
adapter = new QuestionsListAdapter(timeLineItems, this);
listView.setAdapter(adapter); // Cut from Here
And paste in this method:
private void parseJsonFeed(String response) {
try {
JSONObject jsonObj = new JSONObject(response);
JSONArray feedArray = jsonObj.getJSONArray("data");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
QuestionsItem item = new QuestionsItem();
item.setId(feedObj.getInt("id"));
item.setQuestion(feedObj.getString("question"));
String options = feedObj.getString("multi_ans_option");
String[] parts = options.split("\\|");
String part1 = parts[0];
String part2 = parts[1];
String part3 = parts[2];
String part4 = parts[3];
item.setAnsOne(part1);
item.setAnsTwo(part2);
item.setAnsThree(part3);
item.setAnsFour(part4);
item.setAnswer(feedObj.getString("answer"));
timeLineItems.add(item);
listView.setAdapter(adapter); //Paste Here
}
// notify data changes to list adapater
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
I am new to android and don't know what approach I am following is right or wrong.What I am trying to do is to pass the value of two edittexts and one spinner to a API post request on a button click and get the required list of tolls from the response from that API created,and populate a recyclerview just below the clicked button.But the API returns a status 500 i.e. validation error telling the three fields are required.Can anyone tell me where I am doing wrong in accomplishing that task.
Here is my OneTimePaymentActivity.java
public class OneTimePayActivity extends AppCompatActivity {
private Toolbar toolbar;
private EditText etSource, etDest;
private Spinner spinner;
private AppCompatButton payNow;
private LoginActivity LA;
private RecyclerView otp_rec_view;
private ArrayList<OneTimePayModel> oneTimePayModelArrayList;
private String textFromSpinner, etSourceText, etDestText, spinnerItemText, url = "https://tollsuvidha-api.000webhostapp.com/public/api/users/toll-list";
private int id;
private float tollAmtfloat;
private String tollName, city, tollAmountString;
OneTimePayModel oneTimePayModel;
ProgressDialog progressDialog;
private TextView tvFromSpinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_one_time_pay);
etSource = (EditText) findViewById(R.id.etSource);
etDest = (EditText) findViewById(R.id.etDest);
tvFromSpinner = (TextView) findViewById(R.id.textFromSpinner);
toolbar = (Toolbar) findViewById(R.id.toolbarReg);
setSupportActionBar(toolbar);
oneTimePayModelArrayList = new ArrayList<>();
otp_rec_view = (RecyclerView) findViewById(R.id.otp_rec_view);
otp_rec_view.setHasFixedSize(true);
oneTimePayModel = new OneTimePayModel();
progressDialog = new ProgressDialog(OneTimePayActivity.this);
progressDialog.setTitle("Please Wait...");
progressDialog.setMessage("Posting data");
LinearLayoutManager llm = new LinearLayoutManager(this);
llm.setOrientation(LinearLayoutManager.VERTICAL);
otp_rec_view.setLayoutManager(llm);
spinner = (Spinner) findViewById(R.id.spinner1);
etSource = (EditText) findViewById(R.id.etSource);
etDest = (EditText) findViewById(R.id.etDest);
payNow = (AppCompatButton) findViewById(R.id.paynowButton);
LA = new LoginActivity();
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.dd_vehicle_type, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
spinnerItemText = parent.getItemAtPosition(position).toString();
tvFromSpinner.setText(spinnerItemText);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
payNow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
etSourceText = etSource.getText().toString();
etDestText = etDest.getText().toString();
textFromSpinner = tvFromSpinner.getText().toString();
if (!LA.isNetworkAvailable(OneTimePayActivity.this)) {
Toast.makeText(OneTimePayActivity.this, "Please check your internet connection", Toast.LENGTH_LONG).show();
} else if (etSourceText.equals("") || etDestText.equals("")) {
Toast.makeText(getApplicationContext(), "Fields are empty", Toast.LENGTH_LONG).show();
} else {
sendRequest();
}
}
private void sendRequest() {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, (String) null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
progressDialog.show();
int status = response.getInt("status");
if (status == 200) {
Toast.makeText(OneTimePayActivity.this, "Payment Success", Toast.LENGTH_LONG).show();
String message = response.getString("message");
JSONArray data = response.getJSONArray("data");
oneTimePayModelArrayList.clear();
for (int i = 0; i < data.length(); i++) {
JSONObject jobj = data.getJSONObject(0);
id = jobj.getInt("id");
tollName = jobj.getString("toll_name");
city = jobj.getString("city");
tollAmountString = jobj.getString(textFromSpinner + "_price");
tollAmtfloat = Float.parseFloat(tollAmountString);
oneTimePayModel.setId(id);
oneTimePayModel.setTollHead(tollName);
oneTimePayModel.setTollLocation(city);
oneTimePayModel.setTollAmount(tollAmtfloat);
oneTimePayModelArrayList.add(oneTimePayModel);
}
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
} else if (status == 500) {
String message = response.getString("message");
Toast.makeText(OneTimePayActivity.this, message, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
OneTimePayAdapter adapter = new OneTimePayAdapter(oneTimePayModelArrayList);
otp_rec_view.setAdapter(adapter);
adapter.notifyDataSetChanged();
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("source", etSourceText);
params.put("destination", etDestText);
params.put("vehicle_type", textFromSpinner);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(MyApplication.getContext());
requestQueue.add(jsonObjectRequest);
}
});
}
}
I even tried to debug the app and see the values of the texts passed to the API.But even if the texts passed are non-empty,it always returns a status=500(validation error) instead of status=200(Successful response).
Here is my layout file of the above activity
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include
android:id="#+id/toolBarOTP"
layout="#layout/titlebar" />
<TextView
android:id="#+id/onetimeText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/toolBarOTP"
android:text="#string/one_time_payment"
android:textColor="#color/black"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="#+id/textFromSpinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/onetimeText" />
<android.support.design.widget.TextInputLayout
android:id="#+id/textInputSource"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/textFromSpinner"
android:layout_marginTop="20dp">
<EditText
android:id="#+id/etSource"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_marginTop="10dp"
android:hint="#string/source"
android:inputType="text" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="#+id/textInputDest"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/textInputSource">
<EditText
android:id="#+id/etDest"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
android:hint="#string/dest"
android:inputType="text" />
</android.support.design.widget.TextInputLayout>
<Spinner
android:id="#+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/textInputDest"
android:drawSelectorOnTop="true" />
<android.support.v7.widget.AppCompatButton
android:id="#+id/paynowButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/spinner1"
android:layout_marginTop="20dp"
android:text="#string/pay_now"
android:textSize="20sp" />
<android.support.v7.widget.RecyclerView
android:id="#+id/otp_rec_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/paynowButton"
android:layout_marginTop="10dp" />
</RelativeLayout>
and here is the screenshot of the layout of activity_one_time_pay.xml:
I struggled to find a solution to this for 3 hours,but could not find anything specific.Please tell me a correct way to do it.
Take value in String variable and set that variable global for class.
You should try this :
String spinnerItemText = parent.getItemAtPosition(position).toString();
Want integer value :
Int value=Integer.parseInt(spinnerItemText).
Have you tried
String text = spinner.getSelectedItem().toString();
Try this,
ArrayList<String> spinnerData = Arrays.asList(getResources().getStringArray(R.array.dd_vehicle_type));
spinnerData.get(spinner.getSelectedItemPosition());
Even I have had the same problem and this worked out for me.
Sorry for suuuuch a late reply, but I got busy somewhere and almost forgot that I had asked a question and wanted a solution for that ASAP.
And thanks a lot for posting such awesome answers to my question.
But I must tell you that I had found a working solution for my problem.
Here are the changes I have done to my code to make it work
OneTimePaymentActivity.java
The only major change I have made in the code are here
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { <-----------
i.e using the StringRequest instead of JsonObjectRequest
and here
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest); <--------
progressDialog = new ProgressDialog(OneTimePayActivity.this);
progressDialog.setTitle("Please Wait...");
progressDialog.setMessage("Fetching data");
progressDialog.setCancelable(false);
progressDialog.show();
}
i.e passing stringRequest to RequestQueue above
}
The rest of the code is same.
If anyone is facing any difficulty understanding the changes I have made in the code, please leave a comment below.
I have problem when i get the list from server i want to check it, if it's any object there or not.
if there are object , appears in my layout text : there is no object after few seconds it's disappears
and show my list.
i want just if there is object will appear in my layout directly.
private class RetrieveTask extends AsyncTask> {
#Override
protected List<branch> doInBackground(String... params) {
manager = new SessionManager(getActivity().getApplicationContext());
manager.checkLogin();
HashMap<String, String> user = manager.getUserID();
String uid = user.get(SessionManager.KEY_uid);
// Intent intent= getActivity().getIntent(); // gets the previously created intent
//String type18 = intent.getStringExtra("key28");
String strUrl =
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(strUrl);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("markers");
////////////////////////////////////////
List<branch> bList = new ArrayList<>();
Gson gson = new Gson();
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
/////////market object
market mr = new market(Integer.valueOf(finalObject.getString("id")), finalObject.getString("mName")
, finalObject.getString("pic"));
/////////location object
location lo = new location(Float.valueOf(finalObject.getString("lat")), Float.valueOf(finalObject.getString("lng"))
, finalObject.getString("area"), finalObject.getString("city"));
/////////(branch object) inside it (market object)
branch it = new branch(Integer.valueOf(finalObject.getString("bid")), Integer.valueOf(finalObject.getString("phone"))
, finalObject.getString("ser"), Integer.valueOf(finalObject.getString("dis")), Integer.valueOf(finalObject.getString("brNo"))
, Float.valueOf(finalObject.getString("rating")), mr, lo,true);
/*//////////add marker
LatLng latlng = new LatLng(Double.valueOf(finalObject.getString("lat")), Double.valueOf(finalObject.getString("lng")));
addMarker(latlng, Integer.valueOf(finalObject.getString("bid")));*/
// adding the branch object in the list
bList.add(it);
}
return bList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
here the postExcute
#Override
protected void onPostExecute(final List<branch> result) {
super.onPostExecute(result);
if (result != null) {
final itemAdapter adapter = new itemAdapter(getActivity().getApplicationContext(), R.layout.row_favmarkets, result);
lv.setAdapter(adapter);
}
}
}
this is my layout xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="4dp"
android:paddingLeft="4dp"
android:paddingRight="4dp"
android:paddingTop="4dp"
tools:context="com.gmplatform.gmp.favouriteitem">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textView28"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="40dp"
android:layout_marginTop="250dp"
android:text="There is no Markets in your Favourite List.."
android:textSize="24sp"
android:visibility="gone" />
</LinearLayout>
<ListView
android:id="#+id/l20"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:horizontalSpacing="3dp"
android:numColumns="3"
android:verticalSpacing="0dp" />
<Button
android:text="Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button6"
android:layout_marginLeft="400dp" />
Suggested changes which will at first show nothing when the request is executed. Once completed, if the list is empty it'll show "There is no Markets in your Favourite List..", otherwise the list will show.
Part Layout XML:
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/linearLayout28">
<TextView
android:id="#+id/textView28"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="40dp"
android:layout_marginTop="250dp"
android:text="There is no Markets in your Favourite List.."
android:textSize="24sp"
android:visibility="gone" />
</LinearLayout>
Initialize linearLayout28:
LinearLayout linearLayout28 = findViewById(R.id.linearLayout28);
And changes for the AsyncTask:
private class RetrieveTask extends AsyncTask<Void, Void, List<branch>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
lv.setVisibility(View.GONE);
linearLayout28.setVisibility(View.GONE);
}
#Override
protected List<branch> doInBackground(String... params) {
//Keep as your code
...
}
#Override
protected void onPostExecute(final List<branch> result) {
super.onPostExecute(result);
if (result != null && result.size() != 0) {
final itemAdapter adapter = new itemAdapter(
getActivity().getApplicationContext(),
R.layout.row_favmarkets, result);
lv.setAdapter(adapter);
lv.setVisibility(View.VISIBLE);
linearLayout28.setVisibility(View.GONE);
} else {
lv.setVisibility(View.GONE);
linearLayout28.setVisibility(View.VISIBLE);
}
}
}
You are basically on the solution but you should not update the user interface from your AsyncTask. Create an interface and implement it on the Activity. Let the activity to update the data on the UI when data is ready or show a message error.
As an example, define the interface in your AsyncTask like:
private TaskCallback listener = null;
public interface TaskCallback {
void OnTaskCompleted ();
}
public void setListener (TaskCallback listener) {
this.listener = listener;
}
When your task was completed:
#Override
public void onPostExecute (Void v) {
if (listener != null) {
listener.OnTaskCompleted ();
}
}
You can add parameters to your callback base on your needs.
At your Activity level:
public class YourActivity extends Activity implements YourTask.TaskCallback {
// When you execute your task add the reference to the listener
YourTask task = new YourTask (YourActivity.this);
task.setListener (YourActivity.this);
task.execute ();
#Override
public void OnTaskCompleted () {
// Update your screen or show an error message
}
}
Basically this question is an update for this question
Just to rewind again, this is the country_info.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="6dip" >
<LinearLayout
android:id="#+id/gambar_saja"
android:layout_width="150dp"
android:layout_height="160dp"
android:orientation="vertical">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/n1"/>
</LinearLayout>
<RelativeLayout
android:id="#+id/detail_country"
android:layout_width="match_parent"
android:layout_height="160dp"
android:layout_toRightOf="#+id/gambar_saja"
android:layout_toEndOf="#+id/gambar_saja"
android:orientation="vertical"
android:layout_marginLeft="4dp">
<TextView
android:id="#+id/code"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="TextView"
android:textSize="24sp"
android:textStyle="bold"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_marginBottom="4dp"/>
<TextView
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/code"
android:layout_below="#+id/code"
android:text="TextView"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_marginBottom="4dp"/>
<TextView
android:id="#+id/continent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/name"
android:layout_below="#+id/name"
android:text="TextView"
android:textSize="14sp"
android:textColor="#android:color/black"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_marginBottom="4dp"/>
<TextView
android:id="#+id/region"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/continent"
android:layout_below="#+id/continent"
android:text="TextView"
android:textSize="14sp"
android:textColor="#android:color/black"
android:textAppearance="?android:attr/textAppearanceMedium"/>
</RelativeLayout>
</RelativeLayout>
and here is cari_studio.xml to populate the country_info into listview (listView1) :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#android:color/white">
<RelativeLayout
android:id="#+id/area"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#color/white"
android:orientation="horizontal" >
<TextView
android:id="#+id/isiArea"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:background="#drawable/text_selector"
android:gravity="center_vertical"
android:paddingBottom="10dp"
android:paddingLeft="35dp"
android:paddingRight="5dp"
android:paddingTop="10dp"
android:text="#string/area"
android:textColor="#color/black"
android:textSize="14sp"
android:visibility="visible"/>
<Spinner
android:id="#+id/textArea"
android:layout_marginRight="15dp"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="#string/area"
android:textColor="#color/black"
android:inputType="text"
android:textSize="14sp"/>
</LinearLayout>
</RelativeLayout>
<RelativeLayout
android:id="#+id/list_area_studio"
android:layout_below="#+id/area"
android:layout_width="match_parent"
android:layout_height="fill_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:padding="10dp"
android:text="#string/cari_studio" android:textSize="20sp" />
<EditText android:id="#+id/myFilter" android:layout_width="match_parent"
android:layout_height="wrap_content" android:ems="10"
android:hint="#string/studio_hint">
<requestFocus />
</EditText>
<ListView android:id="#+id/listView1" android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
</RelativeLayout>
<RelativeLayout
android:id="#+id/bottom_navigation_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RadioGroup
android:id="#+id/radiogroup"
android:layout_width="fill_parent"
android:layout_height="60dp"
android:layout_alignParentBottom="true"
android:orientation="horizontal"
android:background="#drawable/navbar_background"
>
<RadioButton
android:id="#+id/btnAll"
style="#style/navbar_button"
android:drawableTop="#drawable/navbar_allselector"
android:text="All"
/>
<RadioButton
android:id="#+id/btnPicture"
style="#style/navbar_button"
android:drawableTop="#drawable/navbar_pictureselector"
android:text="Pictures"
android:layout_marginLeft="5dp"
/>
<RadioButton
android:id="#+id/btnVideo"
style="#style/navbar_button"
android:drawableTop="#drawable/navbar_videoselector"
android:text="Videos"
android:layout_marginLeft="5dp"
/>
<RadioButton
android:id="#+id/btnFile"
style="#style/navbar_button"
android:drawableTop="#drawable/navbar_fileselector"
android:text="Files"
android:layout_marginLeft="5dp"
/>
<RadioButton
android:id="#+id/btnMore"
style="#style/navbar_button"
android:drawableTop="#drawable/navbar_moreselector"
android:text="More"
android:layout_marginLeft="5dp"
/>
</RadioGroup>
<LinearLayout
android:id="#+id/floatingmenu"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:background="#drawable/laysemitransparentwithborders"
android:orientation="vertical"
android:layout_marginBottom="-4dp"
android:visibility="gone"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="5dp"
android:paddingTop="15dp"
android:paddingBottom="15dp"
android:text="Contacts"
android:textColor="#ffffff"
android:textSize="16dp"
/>
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#ff999999"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="5dp"
android:paddingTop="15dp"
android:paddingBottom="15dp"
android:text="Calendar"
android:textColor="#ffffff"
android:textSize="16dp"
/>
</LinearLayout>
</RelativeLayout>
</RelativeLayout>
and here is the Cari Studio Class to get JSONArray result (use post) and I already success get the result :
public class CariStudio extends Activity{
final Context context = this;
MyCustomAdapter dataAdapter = null;
RadioButton radioButton1, radioButton2, radioButton3, radioButton4, radioButton5;
TextView flexlocationid;
Spinner flexlocation;
JSONObject jsonobject;
JSONArray jsonarray;
ArrayList<String> provincelist;
ArrayList<ProvinceModel> province;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cari_studio);
//Generate list View from ArrayList
new DownloadJSON().execute();
addListenerOnButton();
}
public void addListenerOnButton() {
Bundle extras = getIntent().getExtras();
final String token= extras.getString("TOKEN");
radioButton1 = (RadioButton) findViewById(R.id.btnAll);
radioButton1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(context, home.class);
intent.putExtra("TOKEN", token);
startActivity(intent);
}
});
radioButton2 = (RadioButton) findViewById(R.id.btnPicture);
radioButton2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(context, CariKelas.class);
intent.putExtra("TOKEN", token);
startActivity(intent);
}
});
radioButton3 = (RadioButton) findViewById(R.id.btnVideo);
radioButton3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(context, CariStudio.class);
intent.putExtra("TOKEN", token);
startActivity(intent);
}
});
radioButton4 = (RadioButton) findViewById(R.id.btnFile);
radioButton4.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(context, HotStuff.class);
intent.putExtra("TOKEN", token);
startActivity(intent);
}
});
radioButton5 = (RadioButton) findViewById(R.id.btnMore);
radioButton5.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(context, MyAccount.class);
intent.putExtra("TOKEN", token);
startActivity(intent);
}
});
flexlocation = (Spinner) findViewById(R.id.textArea);
flexlocationid = (TextView) findViewById(R.id.isiArea);
}
private class SendfeedbackJob extends AsyncTask<String, Void, String> {
private static final String LOG_TAG = "CariStudio";
ProgressDialog dialog;
Bundle extras = getIntent().getExtras();
final String token= extras.getString("TOKEN");
#Override
protected String doInBackground(String... params) {
String areaid = params[0];
Utils.log("params 1:"+ areaid);
// do above Server call here
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("region_id", areaid ));
String responseString = null;
final String url_studio = Constant.URI_BASE_AVAILABLE_STUDIO+ "?token=" + token;
Utils.log("url studio:"+ url_studio);
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url_studio);
// no idea what this does :)
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
// This is the line that send the request
HttpResponse response = httpclient.execute(httppost);
Utils.log("response:"+ response);
HttpEntity entity = response.getEntity();
String responseAsText = EntityUtils.toString(entity);
Utils.log("daftar isi studio: " + responseAsText);
JSONArray json = new JSONArray(responseAsText);
for (int i = 0; i < json.length(); i++) {
jsonobject = json.getJSONObject(i);
final String studio_name = jsonobject.getString("studio_name");
final String address = jsonobject.getString("address");
final String website = jsonobject.getString("website");
final String seo_url = jsonobject.getString("seo_url");
Utils.log("studio_name: " + studio_name);
runOnUiThread(new Runnable() {
public void run() {
ArrayList<Country> countryList = new ArrayList<Country>();
Country country = new Country(studio_name,address, "Website:"+ website,
"Fasilitas:"+ seo_url);
countryList.add(country);
//create an ArrayAdaptar from the String Array
dataAdapter = new MyCustomAdapter(context,
R.layout.country_info, countryList);
//enables filtering for the contents of the given ListView
ListView listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Country country = (Country) parent.getItemAtPosition(position);
Toast.makeText(getApplicationContext(),
country.getCode(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, checkin.class);
startActivity(intent);
}
});
EditText myFilter = (EditText) findViewById(R.id.myFilter);
myFilter.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
dataAdapter.getFilter().filter(s.toString());
}
});
}
});
}
}
catch (Exception e)
{
/*Toast.makeText(context,
"user not registered", Toast.LENGTH_SHORT).show();*/
Log.e(LOG_TAG, String.format("Error during login: %s", e.getMessage()));
}
return "processing";
}
protected void onPostExecute(Boolean result) {
//dialog.cancel();
}
}
// Download JSON file AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// Locate the CariStudio Class
province = new ArrayList<ProvinceModel>();
// Create an array to populate the spinner
provincelist = new ArrayList<String>();
// JSON file URL address
final String url_flexlocation = Constant.URI_BASE_FLEXLOCATION;
Utils.log("url_flexlocation: " + url_flexlocation);
try {
// Locate the NodeList name
HttpGet httppost = new HttpGet(url_flexlocation);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
Utils.log("data: " + data);
JSONArray json = new JSONArray(data);
for (int i = 0; i < json.length(); i++) {
jsonobject = json.getJSONObject(i);
ProvinceModel worldpop = new ProvinceModel();
worldpop.setId(jsonobject.optString("flex_id"));
worldpop.setProvince(jsonobject.optString("name"));
province.add(worldpop);
// Populate spinner with province names
provincelist.add(jsonobject.optString("name"));
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the spinner in cari_studio.xml
Spinner mySpinner = (Spinner) findViewById(R.id.textArea);
// Spinner adapter
mySpinner
.setAdapter(new ArrayAdapter<String>(CariStudio.this,
R.layout.spinner_white,
provincelist));
// Spinner on item click listener
mySpinner
.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0,
View arg1, int position, long arg3) {
// TODO Auto-generated method stub
// Locate the textviews in cari_studio.xml
TextView flexlocationid = (TextView) findViewById(R.id.isiArea);
// Set the text followed by the position
flexlocationid.setText(province.get(position).getId());
String areaid = flexlocationid.getText().toString();
Utils.log("area id:" + areaid);
SendfeedbackJob job = new SendfeedbackJob();
job.execute(areaid);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
private class MyCustomAdapter extends ArrayAdapter<Country> {
private ArrayList<Country> originalList;
private ArrayList<Country> countryList;
private CountryFilter filter;
public MyCustomAdapter(Context context, int textViewResourceId,
ArrayList<Country> countryList) {
super(context, textViewResourceId, countryList);
this.countryList = new ArrayList<Country>();
this.countryList.addAll(countryList);
this.originalList = new ArrayList<Country>();
this.originalList.addAll(countryList);
}
#Override
public Filter getFilter() {
if (filter == null){
filter = new CountryFilter();
}
return filter;
}
private class ViewHolder {
TextView code;
TextView name;
TextView continent;
TextView region;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.country_info, null);
holder = new ViewHolder();
holder.code = (TextView) convertView.findViewById(R.id.code);
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.continent = (TextView) convertView.findViewById(R.id.continent);
holder.region = (TextView) convertView.findViewById(R.id.region);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Country country = countryList.get(position);
holder.code.setText(country.getCode());
holder.name.setText(country.getName());
holder.continent.setText(country.getContinent());
holder.region.setText(country.getRegion());
return convertView;
}
private class CountryFilter extends Filter
{
#Override
protected FilterResults performFiltering(CharSequence constraint) {
constraint = constraint.toString().toLowerCase();
FilterResults result = new FilterResults();
if(constraint != null && constraint.toString().length() > 0)
{
ArrayList<Country> filteredItems = new ArrayList<Country>();
for(int i = 0, l = originalList.size(); i < l; i++)
{
Country country = originalList.get(i);
if(country.toString().toLowerCase().contains(constraint))
filteredItems.add(country);
}
result.count = filteredItems.size();
result.values = filteredItems;
}
else
{
synchronized(this)
{
result.values = originalList;
result.count = originalList.size();
}
}
return result;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
countryList = (ArrayList<Country>)results.values;
notifyDataSetChanged();
clear();
for(int i = 0, l = countryList.size(); i < l; i++)
add(countryList.get(i));
notifyDataSetInvalidated();
}
}
}
}
the result that I got from Utils.log("daftar isi studio: " + responseAsText) :
[{"id":"8","studio_name":"Dodi fit","seo_url":"dodi-fit","address":"Komp. Pertanian Blok 5 No 3","postcode":"87473","area_phone":"","phone":"+62876543","area_phone_second":"","phone_second":"+62","website":"sucifir.com","region_id":"12","lokasi_id":"138","booking_window":"7","facebook":"dodifitfb","twitter":"dodifittw","how_to_get_there":"over there, by trun left and right","priority":"5"},{"id":"11","studio_name":"inu fit","seo_url":"inu-fit","address":"","postcode":"","area_phone":"","phone":"+6221324234","area_phone_second":"","phone_second":"","website":"","region_id":"11","lokasi_id":"137","booking_window":"0","facebook":"","twitter":"","how_to_get_there":"","priority":"5"},{"id":"5","studio_name":"Vstudio","seo_url":"vstudio","address":"Plaza Indonesia Ground Floor #541","postcode":"","area_phone":"","phone":"+6221453787","area_phone_second":"","phone_second":"","website":"www.jkiij.com","region_id":"12","lokasi_id":"137","booking_window":"0","facebook":"face","twitter":"twy","how_to_get_there":"","priority":"5"},{"id":"7","studio_name":"Infovendor","seo_url":"infovendor","address":"","postcode":"","area_phone":"","phone":"+6221123452","area_phone_second":"","phone_second":"","website":"www.kidsdngf.com","region_id":"12","lokasi_id":"135","booking_window":"1","facebook":"","twitter":"","how_to_get_there":"","priority":"5"},{"id":"12","studio_name":"Seleb Fitnes One","seo_url":"selebfitnesone-57","address":"Kelapa gading timur no 17","postcode":"","area_phone":"","phone":"+6221453777","area_phone_second":"","phone_second":"","website":"selebfirnes.com","region_id":"12","lokasi_id":"138","booking_window":"0","facebook":"","twitter":"","how_to_get_there":"","priority":"5"},{"id":"14","studio_name":"Riri Studio","seo_url":"riristudio-57","address":"Mall Kelapa Gading, Lt 5","postcode":"","area_phone":"","phone":"+6221459325","area_phone_second":"","phone_second":"","website":"riri-riri.com","region_id":"12","lokasi_id":"135","booking_window":"7","facebook":"","twitter":"","how_to_get_there":"","priority":"5"},{"id":"19","studio_name":"NF Studio","seo_url":"nf-studio","address":"Ruko Mediterania Blok A4 No 79Jalan Ahmad Yani Kav A5, Kota Bekasi","postcode":"13536","area_phone":"","phone":"+62265111222","area_phone_second":"","phone_second":"","website":"nfstudio.com","region_id":"11","lokasi_id":"137","booking_window":"7","facebook":"","twitter":"","how_to_get_there":"","priority":"5"}]
and the result that I got from looping Utils.log("studio_name: " + studio_name) are :
studio_name: Dodi fit
studio_name: inu fit
studio_name: Vstudio
studio_name: Infovendor
studio_name: Seleb Fitnes One
studio_name: Riri Studio
studio_name: NF Studio
It means I already got all of it use looping.
But the problem is the result did not populate into listview (it show as one one last result NF Studio, the other did not appear).
What I need is populate this into 4 texview from country_info (I disable imageview) :
String studio_name, address, website, seo_url
What is the correct code to show/populate that into listview?
Add the values into a List and pass it to the Adapter class of your ListView inside onPostExecute()
You don't need a thread, that's the whole point of async.
List View code is in the for loop
UI code belongs to PostExecute() not doInBackground()
You reinitialized the list inside of the loop
Try like this:
private class SendfeedbackJob extends AsyncTask<String, Void, String> {
private static final String LOG_TAG = "CariStudio";
private ArrayList<Country> countryList = new ArrayList<Country>();
ProgressDialog dialog;
Bundle extras = getIntent().getExtras();
final String token= extras.getString("TOKEN");
#Override
protected String doInBackground(String... params) {
String areaid = params[0];
Utils.log("params 1:"+ areaid);
// do above Server call here
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("region_id", areaid ));
String responseString = null;
final String url_studio = Constant.URI_BASE_AVAILABLE_STUDIO+ "?token=" + token;
Utils.log("url studio:"+ url_studio);
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url_studio);
// no idea what this does :)
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
// This is the line that send the request
HttpResponse response = httpclient.execute(httppost);
Utils.log("response:"+ response);
HttpEntity entity = response.getEntity();
String responseAsText = EntityUtils.toString(entity);
Utils.log("daftar isi studio: " + responseAsText);
JSONArray json = new JSONArray(responseAsText);
for (int i = 0; i < json.length(); i++) {
jsonobject = json.getJSONObject(i);
final String studio_name = jsonobject.getString("studio_name");
final String address = jsonobject.getString("address");
final String website = jsonobject.getString("website");
final String seo_url = jsonobject.getString("seo_url");
Utils.log("studio_name: " + studio_name);
Country country = new Country(studio_name,address, "Website:"+ website,"Fasilitas:"+ seo_url);
countryList.add(country);
}
}
catch (Exception e)
{
/*Toast.makeText(context,
"user not registered", Toast.LENGTH_SHORT).show();*/
Log.e(LOG_TAG, String.format("Error during login: %s", e.getMessage()));
}
return "processing";
}
protected void onPostExecute(Boolean result) {
//dialog.cancel();
//create an ArrayAdaptar from the String Array
dataAdapter = new MyCustomAdapter(context,
R.layout.country_info, countryList);
//enables filtering for the contents of the given ListView
ListView listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Country country = (Country) parent.getItemAtPosition(position);
Toast.makeText(getApplicationContext(),
country.getCode(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, checkin.class);
startActivity(intent);
}
});
EditText myFilter = (EditText) findViewById(R.id.myFilter);
myFilter.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
dataAdapter.getFilter().filter(s.toString());
}
});
}
}
I am new to android and I am trying to create a list view using an array adapter, a run method and multi threading. The list displays all the data from an array list as a single row.
My MainActivity looks like this:
public class MainActivity extends FragmentActivity implements OnClickListener{
..
ArrayList<StorylineData> storylineData;
ArrayList<SummaryData> summary;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSpinnerAPI = (Spinner) findViewById(R.id.spinnerAPI);
mButtonSubmit = (Button) findViewById(R.id.buttonSubmit);
mEditTextResponse = (ListView) findViewById(R.id.editResponse);
mProgressRequest = (ProgressBar) findViewById(R.id.progressRequest);
mButtonSubmit.setOnClickListener(this);
...
#Override
public void onClick(View v) {
toggleProgress(true);
switch (mSpinnerAPI.getSelectedItemPosition()) {
case 0: // Authenticate
...
case 4: // Get Summary Day
MovesAPI.getSummary_SingleDay(summaryHandler, "20150418", null);//Date changed to "20150117"
break;
...
case 10: // Get Storyline Day
MovesAPI.getStoryline_SingleDay(storylineHandler, "20150418", "20140714T073812Z", false);//Date changed to "20150418" "null changed to"20140714T073812Z"
break;
...
toggleProgress(false);
break;
}
}
...
private MovesHandler<ArrayList<StorylineData>> storylineHandler = new MovesHandler<ArrayList<StorylineData>>() {
#Override
public void onSuccess(ArrayList<StorylineData> result) {
toggleProgress(false);
updateResponse(
"Date:\t" + result.get(0).getDate() + "\n"
+ "-----------Activity 1 Summary--------\t" + "\n"
+ "Activity:\t" + result.get(0).getActivity().toString() + "\n"//returns 1587 with .getCaloriesIdle()
...
+ "-----------Activity 2 Summary---------\t" + "\n"
+ "Activity:\t" + result.get(0).getSummary().get(0).getActivity() + "\n"//returns 1587 with .getCaloriesIdle()
...
+ "-----------Segments---------\t" + "\n"
+ "Type:\t" + result.get(0).getSegments().get(0).getType() + "\n"//returns 1587 with .getCaloriesIdle()
...
}
public void updateResponse(final String message) {
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
mButtonSubmit.setText(message);
StorylineAdapter adapter = new StorylineAdapter(MainActivity.this, R.layout.item_storyline, storylineData);
mEditTextResponse.setAdapter(adapter);
}
});
}
}
My ArrayAdapter class looks like this:
public class StorylineAdapter extends ArrayAdapter<SummaryData>{
private Context context;
private Runnable runnable;
private ArrayList<StorylineData> storylineData;
public StorylineAdapter(Context context, int resource, ArrayList<SummaryData> objects) {
super(context, resource, objects);
this.context = context;
this.runnable = runnable;
this.summary = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.item_storyline, parent, false);
//Display in the TextView widget
SummaryData summary1 = summary.get(position);
TextView tv = (TextView) view.findViewById(R.id.textView1);
tv.setText(summary1.getActivity());
return view;
}
}
Here is my parser class:
public class StorylineData extends ArrayList<StorylineData> {
...Getters/Setters...
/**
* Parse a {#link org.json.JSONObject} from storyline {#link org.json.JSONArray}, then return the corresponding {#link StorylineData} object.
*
* #param jsonObject : the storyline JSON object received from server
* #return corresponding {#link StorylineData}
*/
public static StorylineData parse(JSONObject jsonObject) throws JSONException {
if (jsonObject != null) {
StorylineData storylineData = new StorylineData();
storylineData.date = jsonObject.optString("date");
storylineData.caloriesIdle = jsonObject.optInt("caloriesIdle");
storylineData.lastUpdate = jsonObject.optString("lastUpdate");
storylineData.summary = new ArrayList<SummaryData>();
storylineData.segments = new ArrayList<SegmentData>();
/**Get the data associated with the array named summary **To get a specific JSONArray: Summary*/
JSONArray summariesJsonArray = jsonObject.optJSONArray("summary");
if (summariesJsonArray != null)
for (int i = 0; i < summariesJsonArray.length(); i++) {
/**each time through array will need to get a reference of current object*/
JSONObject summaryJsonObject = summariesJsonArray.optJSONObject(i);
if (summaryJsonObject != null) {
/**===============Translate data from json to Java=================*/
/**Create a new OBJECT OF ARRAY STORYLINE/SUMMARY*/
ArrayList<SummaryData> summary = new ArrayList<SummaryData>(); // initialisation must be outside the loop
storylineData.setSummary(summary);
/**Get summary from json into java*/
summariesJsonArray.getJSONObject(i).getString("distance");
/**Get date from json into java*/
String date = summaryJsonObject.optString("date");
storylineData.setDate(date);
/**Get group from json into java*/
String group = summaryJsonObject.optString("group");//Get name using key e.g. date
storylineData.setGroup(group);
...
storylineData.summary.add(SummaryData.parse(summaryJsonObject));
Log.d("StorylineDataCls \t sJo", summaryJsonObject.toString() + "Log\n");
System.out.println("print distance" + summariesJsonArray.getJSONObject(i).getString("distance"));
System.out.println("print summary" + summaryJsonObject);
}
}
JSONArray segmentsJsonArray = jsonObject.optJSONArray("segments");
if (segmentsJsonArray != null) {
for (int i = 0; i < segmentsJsonArray.length(); i++) {
JSONObject segment = segmentsJsonArray.optJSONObject(i);
if (segment != null) {
ArrayList<SegmentData> segments = new ArrayList<SegmentData>(); // initialisation must be outside the loop
storylineData.setSegments(segments);
String type = segment.optString("type");
storylineData.setType(type);
...
storylineData.segments.add(SegmentData.parse(segment));
Log.d("StorylineDataCls \t sSo", segment.toString());
}
}
}
return storylineData;
}
return null;
}
}
I'm wondering if the reason the items are appearing in a single row may be because of a problem in the layout files?
Main Layout.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Spinner
android:id="#+id/spinnerAPI"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:entries="#array/API_Names"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:id="#+id/buttonSubmit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Get Data"
android:layout_below="#+id/spinnerAPI"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<ProgressBar
android:id="#+id/progressRequest"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="gone"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/editResponse"
android:layout_below="#+id/spinnerAPI"
android:layout_alignLeft="#+id/progressRequest"
android:layout_alignStart="#+id/progressRequest" />
</RelativeLayout>
Item Layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_centerVertical="true"
android:text="#string/flower_name_placeholder"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
Changed MainActivity to implement View.OnClickListener:
public class MainActivity extends FragmentActivity implements View.OnClickListener {
Removed ArrayAdapter and replaced updateResponse method with:
public void updateResponse(final String message) {
runOnUiThread(new Runnable() {
//MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
ListView mListView = (ListView) findViewById(R.id.list_view);
String[] stringArray = message.split("\n");
// This is the array adapter, it takes the context of the activity as a
// first parameter, the type of list view as a second parameter and your
// array as a third parameter.
ArrayAdapter<String> adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, stringArray);
mListView.setAdapter(adapter);
}
});
}