In my app I am fetching the order details from the mysql db and based on the number of rows in db I am dynamically adding the TextView in my LinearLayout in the app(if there are 6 rows then 6 text views will be displayed in the app)
In doing the toolbar is disabled from the Activity and due to this i am NOT able to go back to my parent activity
I am NOT sure but I think using setLayoutParams is the culprit here.
Please help!
public class OrderHistory extends AppCompatActivity {
private EditText editTextId;
private Button buttonGet;
private TextView textViewResult;
private ProgressDialog loading;
private ScrollView scrollView;
private LinearLayout linearLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_history);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getData(); //get data from the db
}
private void getData() {
//getting data from db
}
private void showJSON(String response){
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Constants.JSON_ARRAY);
this.scrollView = (ScrollView) findViewById(R.id.scrollableContents);
this.linearLayout = (LinearLayout) findViewById(R.id.linear);
this.linearLayout.setOrientation(LinearLayout.VERTICAL);
TextView[] t1 = new TextView[result.length()];
TextView[] t2 = new TextView[result.length()];
TextView[] t3 = new TextView[result.length()];
TextView[] t4 = new TextView[result.length()];
TextView[] t5 = new TextView[result.length()];
ImageView[] img = new ImageView[result.length()];
if(result.length()!=0) {
for (int i = 0; i < result.length(); i++) {
JSONObject collegeData = result.getJSONObject(i);
int orderTotal = Integer.parseInt(collegeData.getString(Constants.KEY_AMOUNT).split("\\ ")[0]) - 49;
int total = orderTotal + 49;
switch (collegeData.getString(Constants.KEY_CCAvenueOrderStatus)) {
case "Success":
t1[i] = new TextView(this);
t1[i].setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
//when this is execute the TOOLBAR disappears #i guess
String success = (i + 1) + "." + "Payment of ₹" + collegeData.getString(Constants.KEY_AMOUNT) + " was received by Horoscope Daily !";
t1[i].setTextColor(getResources().getColor(R.color.white));
t1[i].setTextSize(17);
t1[i].setText(Html.fromHtml("<h4>" + success + "</h4>" + "Your transaction was successfull<br> Order Number<br>" + "<b>" + collegeData.getString(Constants.KEY_ORDERID) + "</b>" + "<br>" + collegeData.getString(Constants.KEY_DATE) + "<br>"));
this.linearLayout.addView(t1[i]);
break;
case "Failure":
t1[i] = new TextView(this);
t1[i].setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
String failure = (i + 1) + "." + "Payment of ₹" + collegeData.getString(Constants.KEY_AMOUNT) + " failed !";
t1[i].setTextColor(getResources().getColor(R.color.white));
t1[i].setTextSize(17);
t1[i].setText(Html.fromHtml("<h4>" + failure + "</h4>" + "Your payment has been declined by your bank.Please contact your bank for any queries.If money has been deducted from your account,your bank will inform us within 48 hrs and we will refund the same<br><br> Order Number<br>" + "<b>" + collegeData.getString(Constants.KEY_ORDERID) + "</b>" + "<br>" + collegeData.getString(Constants.KEY_DATE) + "<br>"));
this.linearLayout.addView(t1[i]);
break;
case "Aborted":
t1[i] = new TextView(this);
t1[i].setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
String aborted = (i + 1) + "." + "Payment of ₹" + collegeData.getString(Constants.KEY_AMOUNT) + " failed !";
t1[i].setTextColor(getResources().getColor(R.color.white));
t1[i].setTextSize(17);
t1[i].setText(Html.fromHtml("<h4>" + aborted + "</h4>" + "Your payment has been declined by your bank as the OTP(one time password) entered is incorrect.Please try again with the correct OTP or contact your bank for any queries.<br><br> Order Number<br>" + "<b>" + collegeData.getString(Constants.KEY_ORDERID) + "</b>" + "<br>" + collegeData.getString(Constants.KEY_DATE) + "<br>"));
this.linearLayout.addView(t1[i]);
break;
default:
}
t3[i] = new TextView(this);
t3[i].setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
t3[i].setTextColor(getResources().getColor(R.color.white));
t3[i].setTextSize(17);
t3[i].setText(Html.fromHtml("<h4>You have below Items in your order</h4> <br>" + collegeData.getString(Constants.KEY_ITEM) + " " + "₹ " + orderTotal + " " + collegeData.getString(Constants.KEY_RATTI) + " Ratti" + " " + collegeData.getString(Constants.KEY_QUANTITY) + " Quantity" + "<br>"));
this.linearLayout.addView(t3[i]);
switch (collegeData.getString(Constants.KEY_ITEM)) {
case "Coral":
String uri = "#drawable/ic_coral_moonga"; // where myresource (without the extension) is the file
int imageResource = getResources().getIdentifier(uri, null, getPackageName());
img[i] = new ImageView(this);
img[i].setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
img[i].getLayoutParams().height = 200;
img[i].getLayoutParams().width = 200;
Drawable res = getResources().getDrawable(imageResource);
img[i].setImageDrawable(res);
this.linearLayout.addView(img[i]);
break;
case "Opal":
img[i] = new ImageView(this);
img[i].setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
img[i].getLayoutParams().height = 200;
img[i].getLayoutParams().width = 200;
img[i].setImageDrawable(getResources().getDrawable(getResources().getIdentifier("#drawable/ic_opal", null, getPackageName())));
this.linearLayout.addView(img[i]);
break;
case "Emerald":
img[i] = new ImageView(this);
img[i].setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
img[i].getLayoutParams().height = 200;
img[i].getLayoutParams().width = 200;
img[i].setImageDrawable(getResources().getDrawable(getResources().getIdentifier("#drawable/ic_emerald_panna", null, getPackageName())));
this.linearLayout.addView(img[i]);
break;
case "Pearl":
img[i] = new ImageView(this);
img[i].setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
img[i].getLayoutParams().height = 200;
img[i].getLayoutParams().width = 200;
img[i].setImageDrawable(getResources().getDrawable(getResources().getIdentifier("#drawable/ic_pearl_moti", null, getPackageName())));
this.linearLayout.addView(img[i]);
break;
case "Ruby":
img[i] = new ImageView(this);
img[i].setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
img[i].getLayoutParams().height = 200;
img[i].getLayoutParams().width = 200;
img[i].setImageDrawable(getResources().getDrawable(getResources().getIdentifier("#drawable/ic_ruby_manikya", null, getPackageName())));
this.linearLayout.addView(img[i]);
break;
case "Yellow Sapphire":
img[i] = new ImageView(this);
img[i].setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
img[i].getLayoutParams().height = 200;
img[i].getLayoutParams().width = 200;
img[i].setImageDrawable(getResources().getDrawable(getResources().getIdentifier("#drawable/ic_yellow_sapphire_pikhraj", null, getPackageName())));
this.linearLayout.addView(img[i]);
break;
case "Blue Sapphire":
img[i] = new ImageView(this);
img[i].setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
img[i].getLayoutParams().height = 200;
img[i].getLayoutParams().width = 200;
img[i].setImageDrawable(getResources().getDrawable(getResources().getIdentifier("#drawable/ic_blue_sapphire", null, getPackageName())));
this.linearLayout.addView(img[i]);
break;
default:
break;
}
t4[i] = new TextView(this);
t4[i].setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
t4[i].setTextColor(getResources().getColor(R.color.white));
t4[i].setTextSize(17);
t4[i].setText(Html.fromHtml("<br><h4>Payment Details</h4> CC Tracking ID <br>" + collegeData.getString(Constants.KEY_CCAvenueTacking_id) + "<br>"));
this.linearLayout.addView(t4[i]);
t5[i] = new TextView(this);
t5[i].setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
t5[i].setText(Html.fromHtml("<h4>Summary</h4> <br>" + "Order Total" + " " + "₹ " + orderTotal + "<br>" + "Shipping" + " " + "₹ 49" + "<br>" + "Total" + " " + "₹ " + total + "<br>"));
t5[i].setTextColor(getResources().getColor(R.color.white));
t5[i].setTextSize(17);
this.linearLayout.addView(t5[i]);
View v = new View(this);
v.setLayoutParams(new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
5
));
v.setBackgroundColor(Color.parseColor("#B3B3B3"));
LinearLayout.LayoutParams margin = (LinearLayout.LayoutParams) v.getLayoutParams();
margin.setMargins(0, 50, 0, 50);
v.setLayoutParams(margin);
this.linearLayout.addView(v);
}
if (this.scrollView.getParent() != null)
((ViewGroup) this.scrollView.getParent()).removeView(this.scrollView);
setContentView(this.scrollView);
}
else{
Toast.makeText(getApplicationContext(),
"No Order History\n"+"Our database indicate that you don't have any orders yet !", Toast.LENGTH_SHORT).show();
// hide the progress dialog
}
} catch (JSONException e) {
e.printStackTrace();
}
// textViewResult.setText("Name:\t"+name+"\nAddress:\t" +address+ "\nVice Chancellor:\t"+ vc);
}
}
Remove this code it is not needed:
if (this.scrollView.getParent() != null)
((ViewGroup)this.scrollView.getParent()).removeView(this.scrollView);
setContentView(this.scrollView);
Move reading from DB to AsyncTask - because you are blocking UI thread on call to getData() and Application freezes durring loading.
Also you need think about using proper container like ListView or RecycleView
I have the list of images in horizontal LinearLayout If I click particular image the same image will appear on the above of single image view.
How can I get the position of Images in Image View.
CODE
JSONArray multipleimage = alertObj.getJSONArray(PRODUCT_IMAGES);
/*JSONObject singleimage = multipleimage.getJSONObject(Integer.parseInt("original_res"));
String singleimg = productpath + alertObj.getString("seller_id") + String.valueOf(singleimage);
firstimages=(ImageView)
findViewById(R.id.singleimage);
YelloPage.imageLoader.displayImage(singleimg,firstimages,options);*/
horizontalimage=(LinearLayout) findViewById(R.id.linearimage);
if(multipleimage.length()>0)
{
for (int j = 0; j < multipleimage.length(); j++) {
JSONObject pimages = multipleimage.getJSONObject(j);
JSONObject oneimage = multipleimage.getJSONObject(0);
ii = new ImageView(singleshooppingcart.this);
multipleimages = (ImageView) findViewById(R.id.singleimage);
ii.setScaleType(ImageView.ScaleType.FIT_CENTER);
LinearLayout.LayoutParams image = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
image.width = 150;
image.height = 150;
image.setMargins(5, 0, 0, 0);
String multimgs = pimages.getString("original_res");
String oneimg = oneimage.getString("original_res");
String[] img2 = multimgs.split("\\.");
String imagone = productpath + alertObj.getString("seller_id") + '/' + img2[0] + '(' + '2' + '0' + '0' + ')' + '.' + img2[1];
String singleiamges = productpath + alertObj.getString("seller_id") + '/' + oneimg;
YelloPage.imageLoader.displayImage(imagone, ii, options);
YelloPage.imageLoader.displayImage(singleiamges, multipleimages, options);
ii.setLayoutParams(image);
horizontalimage.addView(ii);
ii.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
}
How to solve this problem Thanks in Advance.
You can use many approaches for this-
Simplest approach is using ViewGroup#indexOfChild(View child) method. This will simply return what you want.
Or you can use View#setTag(Object) and View#getTag(), specially if you want to get some thing more than mere index in onClick.
You can also use View#setTag(int, Object) and View#getTag(int), if you want to set more than one tag per view.
Hope below example code for first approach helps-
ii.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick (View view){
// the parameter view here is your imageview, which is clicked.
// horizontalimage is your LinearLayout, which is a ViewGroup
int indexOfImage = horizontalimage.indexOfChild(view);
// do what you want to do with index
}
});
Not tested..try like this...
JSONArray multipleimage = alertObj.getJSONArray(PRODUCT_IMAGES);
/*JSONObject singleimage = multipleimage.getJSONObject(Integer.parseInt("original_res"));
String singleimg = productpath + alertObj.getString("seller_id") + String.valueOf(singleimage);
firstimages = (ImageView)findViewById(R.id.singleimage);
YelloPage.imageLoader.displayImage(singleimg,firstimages,options);*/
horizontalimage = (LinearLayout)findViewById(R.id.linearimage);
if(multipleimage.length()>0)
{
for (int j = 0; j < multipleimage.length(); j++) {
JSONObject pimages = multipleimage.getJSONObject(j);
JSONObject oneimage = multipleimage.getJSONObject(0);
ii = new ImageView(singleshooppingcart.this);
multipleimages = (ImageView) findViewById(R.id.singleimage);
ii.setScaleType(ImageView.ScaleType.FIT_CENTER);
LinearLayout.LayoutParams image = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
image.width = 150;
image.height = 150;
image.setMargins(5, 0, 0, 0);
String multimgs = pimages.getString("original_res");
String oneimg = oneimage.getString("original_res");
String[] img2 = multimgs.split("\\.");
String imagone = productpath + alertObj.getString("seller_id") + '/' + img2[0] + '(' + '2' + '0' + '0' + ')' + '.' + img2[1];
String singleiamges = productpath + alertObj.getString("seller_id") + '/' + oneimg;
YelloPage.imageLoader.displayImage(imagone, ii, options);
YelloPage.imageLoader.displayImage(singleiamges, multipleimages, options);
ii.setLayoutParams(image);
horizontalimage.addView(ii);
ii.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
multipleimages.setImageURI (singleiamges);
}
});
}
}
Am trying to create edittext and textview widgets dynamically into program. it works fine. now i want to access the textvalue with its corresponding edittext value. how to do it?
Here is what i have tried.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_callreport);
dcname = ProductdetailsEnd.doctor;
resultArr1 = ProductdetailsEnd.resultArr;
callreportbtn = (Button) findViewById(R.id.callreportbtn);
arraysize = resultArr1.length;
TableLayout tb = (TableLayout) findViewById(R.id.tablelayout);
for (int i = 0; i < arraysize; i++) {
res = resultArr1[i];
TableRow tr = new TableRow(this);
TableRow.LayoutParams pl = new TableRow.LayoutParams(
TableRow.LayoutParams.MATCH_PARENT);
tr.setLayoutParams(pl);
tr.setWeightSum(1.0f);
product = new TextView(this);
product.setLayoutParams(new TableRow.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 0.7f));
product.setId(i);
qty = new EditText(this);
qty.setLayoutParams(new TableRow.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 0.3f));
qty.setId(i);
qty.setWidth(50);
product.setText(res);
tr.addView(product);
tr.addView(qty);
tb.addView(tr, i);
Log.d("Call Report name : ", "" + dcname);
Log.d("Call Report prod :", "" + res);
}
Log.d("res length : ", "" + arraysize);
for (int i = 0; i < arraysize; i++) {
String product1 = resultArr1[i];
String qty1 = qty.getText().toString();
Log.d("products &&: ", "" + product1 + ":" + qty1);
}
callreportbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Hello",
Toast.LENGTH_LONG).show();
for (int i = 0; i < arraysize; i++) {
String product1 = resultArr1[i];
String qty1 = qty.getText().toString();
Log.d("products &&: ", "" + product1 + ":" + qty1);
}
}
});
}
after entering the value, when i say submit it should display the textview value along with edittext value.
For more convenience i have added a snap of my output.
first image to enter the value
second image is output in logcat.
There are many ways to do what you want.
Place your views inside a List object, and read the list when you submit.
Implement TextWatcher interface and record your String values as they change.
Assign an Id to your views, and later retrieve your views by Id.
Third option required you to carefully assign id's, because I think they must be unique. Second option, I think, is best one in many cases, since you may also want to provide some feedback to user.
EDIT:
TextWatcher is interface that receives callbacks from TextView. Simply call addTextChangedListener method and provide a TextWatcher implementation.
aTextView.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
Finally i got the answer. referred this post - Creation of EditText Dynamically and get their text from each of EditText
Created an array of the EditText and accessed it in the button onclick method.
this is my code and its working.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_callreport);
dcname = ProductdetailsEnd.doctor;
resultArr1 = ProductdetailsEnd.resultArr;
callreportbtn = (Button) findViewById(R.id.callreportbtn);
quantity = new ArrayList<EditText>();
arraysize = resultArr1.length;
TableLayout tb = (TableLayout) findViewById(R.id.tablelayout);
for (int i = 0; i < arraysize; i++) {
res = resultArr1[i];
TableRow tr = new TableRow(this);
TableRow.LayoutParams pl = new TableRow.LayoutParams(
TableRow.LayoutParams.MATCH_PARENT);
tr.setLayoutParams(pl);
tr.setWeightSum(1.0f);
product = new TextView(this);
product.setLayoutParams(new TableRow.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 0.7f));
product.setId(i);
qty = new EditText(this);
qty.setLayoutParams(new TableRow.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 0.3f));
//qty.setId(i);
qty.setWidth(50);
product.setText(res);
tr.addView(product);
tr.addView(qty);
tb.addView(tr, i);
quantity.add(qty);
Log.d("Call Report name : ", "" + dcname);
Log.d("Call Report prod :", "" + res);
}
Log.d("res length : ", "" + arraysize);
Log.d("qty length : ", "" + qty.length());
String[] items1 = new String[quantity.size()];
for (int i = 0; i < arraysize; i++) {
String product1 = resultArr1[i];
items1[i] = quantity.get(i).getText().toString();
Log.d("qty id ", "" +qty.toString());
Log.d("products &&: ", "" + product1 + ":" + items1);
}
callreportbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Hello",
Toast.LENGTH_LONG).show();
String[] items = new String[quantity.size()];
for (int i = 0; i < arraysize; i++) {
String product1 = resultArr1[i];
items[i] = quantity.get(i).getText().toString();
Log.d("products &&: ", "" + product1 + ":" + items[i]);
}
}
});
}
How to call AsyncTask class in the fragment class, when i call is not go in the AsyncTask it will return null view what i do ? And my view is created in postExecute afetr i got all the data from doInbackground.
public class ShowResultsFragment extends android.support.v4.app.Fragment {
Context context;
ArrayList<Semester> semesterArrayList;
LayoutInflater inflaterView;
ViewGroup containerView;
View newView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
this.inflaterView = inflater;
this.containerView = container;
context = container.getContext();
new StudentResultAsyncTask().execute();
return newView;
}
public class StudentResultAsyncTask extends AsyncTask {
JSONObject jsonObject = null;
ProgressDialog pDialog;
String jsondata = "{\"1\" :[{\"subName\":\"EG\",\"subCode\":\"1009\",\"subCredit\":\"5\",\"subGrade\":\"AA\"}," +
"{\"subName\":\"ES\",\"subCode\":\"2009\",\"subCredit\":\"6\",\"subGrade\":\"DD\"}," +
"{\"subName\":\"EME\",\"subCode\":\"3009\",\"subCredit\":\"6\",\"subGrade\":\"FF\"}," +
"{\"subName\":\"EEE\",\"subCode\":\"4009\",\"subCredit\":\"7\",\"subGrade\":\"BC\"}," +
"{\"subName\":\"MOS\",\"subCode\":\"5009\",\"subCredit\":\"6\",\"subGrade\":\"FF\"}," +
"{\"subName\":\"M-1\",\"subCode\":\"1009\",\"subCredit\":\"6\",\"subGrade\":\"CD\"}," +
"{\"subName\":\"EE\",\"subCode\":\"45090\",\"subCredit\":\"4\",\"subGrade\":\"AB\"}," +
"{\"subName\":\"ECE\",\"subCode\":\"10090\",\"subCredit\":\"5\",\"subGrade\":\"FF\"}," +
"{\"SPI\":\"1.4\",\"CPI\":\"4.67\"}]," +
"\"2\":[{\"subName\":\"M-2\",\"subCode\":\"111009\",\"subCredit\":\"6\",\"subGrade\":\"DD\"}," +
"{\"subName\":\"Workshop\",\"subCode\":\"1009\",\"subCredit\":\"6\",\"subGrade\":\"AB\"}," +
"{\"subName\":\"CPU\",\"subCode\":\"1009\",\"subCredit\":\"6\",\"subGrade\":\"FF\"}," +
"{\"subName\":\"EG\",\"subCode\":\"1009\",\"subCredit\":\"6\",\"subGrade\":\"CC\"}," +
"{\"subName\":\"M-4\",\"subCode\":\"1009\",\"subCredit\":\"6\",\"subGrade\":\"CD\"}," +
"{\"subName\":\"AE\",\"subCode\":\"103309\",\"subCredit\":\"6\",\"subGrade\":\"CD\"}," +
"{\"subName\":\"EG-1\",\"subCode\":\"11119\",\"subCredit\":\"6\",\"subGrade\":\"CD\"}," +
"{\"subName\":\"AE\",\"subCode\":\"8876\",\"subCredit\":\"6\",\"subGrade\":\"FF\"}," +
"{\"SPI\":\"2.5\",\"CPI\":\"6.67\"}]," +
"\"3\":[{\"subName\":\"M-3\",\"subCode\":\"111009\",\"subCredit\":\"6\",\"subGrade\":\"AA\"}," +
"{\"subName\":\"BE\",\"subCode\":\"1009\",\"subCredit\":\"6\",\"subGrade\":\"AB\"}," +
"{\"subName\":\"DLD\",\"subCode\":\"1009\",\"subCredit\":\"6\",\"subGrade\":\"BB\"}," +
"{\"subName\":\"NCS\",\"subCode\":\"1009\",\"subCredit\":\"6\",\"subGrade\":\"BC\"}," +
"{\"subName\":\"M-4\",\"subCode\":\"1009\",\"subCredit\":\"6\",\"subGrade\":\"CC\"}," +
"{\"subName\":\"AE\",\"subCode\":\"103309\",\"subCredit\":\"6\",\"subGrade\":\"CD\"}," +
"{\"SPI\":\"6.50\",\"CPI\":\"0.67\"}]," +
"\"4\":[{\"subName\":\"AAS\",\"subCode\":\"111009\",\"subCredit\":\"6\",\"subGrade\":\"AB\"}," +
"{\"subName\":\"C++\",\"subCode\":\"1009\",\"subCredit\":\"6\",\"subGrade\":\"AB\"}," +
"{\"subName\":\"Management-1\",\"subCode\":\"1009\",\"subCredit\":\"6\",\"subGrade\":\"AB\"}," +
"{\"subName\":\"EG\",\"subCode\":\"1009\",\"subCredit\":\"6\",\"subGrade\":\"AB\"}," +
"{\"subName\":\"M-4\",\"subCode\":\"1009\",\"subCredit\":\"6\",\"subGrade\":\"AB\"}," +
"{\"subName\":\"AE\",\"subCode\":\"103309\",\"subCredit\":\"6\",\"subGrade\":\"DD\"}," +
"{\"SPI\":\"9.50\",\"CPI\":\"5.67\"}]," +
"\"5\":[{\"subName\":\"WAD\",\"subCode\":\"111022209\",\"subCredit\":\"6\",\"subGrade\":\"FF\"}," +
"{\"subName\":\"AES\",\"subCode\":\"703309\",\"subCredit\":\"6\",\"subGrade\":\"DD\"}," +
"{\"SPI\":\"5.50\",\"CPI\":\"5.67\",\"CGPA\":\"5.67\"}]," +
"\"6\":[{\"subName\":\"SP\",\"subCode\":\"66622209\",\"subCredit\":\"6\",\"subGrade\":\"FF\"}," +
"{\"subName\":\"Parallel\",\"subCode\":\"66622209\",\"subCredit\":\"6\",\"subGrade\":\"AB\"}," +
"{\"subName\":\"Java\",\"subCode\":\"66622209\",\"subCredit\":\"6\",\"subGrade\":\"AB\"}," +
"{\"subName\":\"COA\",\"subCode\":\"66622209\",\"subCredit\":\"6\",\"subGrade\":\"AB\"}," +
"{\"subName\":\"Management\",\"subCode\":\"66622209\",\"subCredit\":\"6\",\"subGrade\":\"FF\"}," +
"{\"subName\":\"TOC\",\"subCode\":\"703309\",\"subCredit\":\"6\",\"subGrade\":\"DD\"}," +
"{\"SPI\":\"5.50\",\"CPI\":\"5.67\",\"CGPA\":\"6.07\"}]," +
"\"7\":[{\"subName\":\"CD\",\"subCode\":\"12522209\",\"subCredit\":\"6\",\"subGrade\":\"AB\"}," +
"{\"subName\":\"WCMP\",\"subCode\":\"12522209\",\"subCredit\":\"6\",\"subGrade\":\"AB\"}," +
"{\"subName\":\"SP\",\"subCode\":\"12522209\",\"subCredit\":\"6\",\"subGrade\":\"AB\"}," +
"{\"subName\":\"Advance Java\",\"subCode\":\"703309\",\"subCredit\":\"6\",\"subGrade\":\"FF\"}," +
"{\"SPI\":\"8.90\",\"CPI\":\"6.09\",\"CGPA\":\"7.77\"}]," +
"\"8\":[{\"subName\":\"Android\",\"subCode\":\77022209\",\"subCredit\":\"6\",\"subGrade\":\"AB\"}," +
"{\"subName\":\"PP\",\"subCode\":2209\",\"subCredit\":\"6\",\"subGrade\":\"BB\"}," +
"{\"subName\":\"DS\",\"subCode\":\"7309\",\"subCredit\":\"6\",\"subGrade\":\"DD\"}," +
"{\"SPI\":\"5.70\",\"CPI\":\"5.97\",\"CGPA\":\"6.85\"}]}";
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setMessage("Loading...");
pDialog.show();
}
#Override
protected String doInBackground(String... params1) {
String key;
Iterator<String> iter;
int length;
/* List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(c.getResources().getString(R.string.keyUsername), Utility.getUsername(c)));
JSONParser jp=new JSONParser();
//jp.makeHttpRequest(c.getResources().getString(R.string.server_name)+ c.getResources().getString(R.string.login_file), "POST", params);
*/ //Todo : delete comment when data is come from server.
try {
jsonObject = new JSONObject(jsondata);
} catch (JSONException e) {
e.printStackTrace();
}
iter = jsonObject.keys();
semesterArrayList = new ArrayList<>();
while (iter.hasNext()) {
key = iter.next();
try {
JSONArray jsonArray = jsonObject.getJSONArray(key);
length = jsonArray.length();
ArrayList<SubjectDetails> saveSubDetailsArrayList = new ArrayList<>();
Semester semDetail = new Semester();
semDetail.setSemester(key);
for (int i = 0; i < length; i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
SubjectDetails subDetails = new SubjectDetails();
if (i == length - 1) {
Float spi = Float.valueOf(jsonObject1.getString(getResources().getString(R.string.server_key_result_SPI)));
Float cpi = Float.valueOf(jsonObject1.getString(getResources().getString(R.string.server_key_result_CPI)));
semDetail.setSpi(spi);
semDetail.setCpi(cpi);
if (key.equals("5") || key.equals("6") || key.equals("7") || key.equals("8")) {
Float cgpi = Float.valueOf(jsonObject1.getString(getResources().getString(R.string.server_key_result_CGPA)));
semDetail.setCgpi(cgpi);
}
} else {
String subname = jsonObject1.getString(getResources().getString(R.string.server_key_result_subName));
String subcode = jsonObject1.getString(getResources().getString(R.string.server_key_result_subCode));
String subcredit = jsonObject1.getString(getResources().getString(R.string.server_key_result_subCredit));
String subgrade = jsonObject1.getString(getResources().getString(R.string.server_key_result_subGrade));
subDetails.setSubname(subname);
subDetails.setSubcode(subcode);
subDetails.setSubcredit(subcredit);
subDetails.setSubgrade(subgrade);
saveSubDetailsArrayList.add(subDetails);
semDetail.setGetSubjectDetails(saveSubDetailsArrayList);
}
}
semesterArrayList.add(semDetail);
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
ListView lv = (ListView) newView.findViewById(R.id.listview);
lv.setAdapter(new ShowResultAdapter(semesterArrayList, context));
pDialog.dismiss();
}
}
and this is my Adapter class...
public class ShowResultAdapter extends BaseAdapter {
ArrayList<Semester> semesterArrayList;
Context c;
LinearLayout linearHeader;
ShowResultAdapter(ArrayList<Semester> saveDetails, Context context)
{
semesterArrayList = saveDetails;
c = context;
}
#Override
public int getCount() {
return semesterArrayList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
LinearLayout linearSub;
LinearLayout linearSpiCpiCgpa;
LayoutInflater inflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.layout_result_adapter, null);
LinearLayout linearLayout = (LinearLayout) view.findViewById(R.id.linear);
TextView sem = new TextView(c);
sem.setGravity(Gravity.CENTER_HORIZONTAL);
sem.setTextSize(20);
sem.setPadding(0, 0, 0, 10);
sem.setTextColor(Color.WHITE);
sem.setText(c.getResources().getString(R.string.result_Semester) + " " + ":" + " " + semesterArrayList.get(position).getSemester());
sem.setPaintFlags(Paint.UNDERLINE_TEXT_FLAG);
linearLayout.addView(sem);
linearHeader = new LinearLayout(c);
linearHeader.setOrientation(LinearLayout.HORIZONTAL);
linearHeader.setWeightSum(4);
TextView name = new TextView(c);
setHeader(name, c.getResources().getString(R.string.server_key_result_subName));
linearHeader.addView(name);
TextView code = new TextView(c);
setHeader(code, c.getResources().getString(R.string.server_key_result_subCode));
linearHeader.addView(code);
TextView credit = new TextView(c);
setHeader(credit, c.getResources().getString(R.string.server_key_result_subCredit));
linearHeader.addView(credit);
TextView grade = new TextView(c);
setHeader(grade, c.getResources().getString(R.string.server_key_result_subGrade));
linearHeader.addView(grade);
linearLayout.addView(linearHeader);
if (semesterArrayList.get(position).getSemester().equals("1") || semesterArrayList.get(position).getSemester().equals("2") || semesterArrayList.get(position).getSemester().equals("3") || semesterArrayList.get(position).getSemester().equals("4")) {
linearSpiCpiCgpa = new LinearLayout(c);
linearSpiCpiCgpa.setOrientation(LinearLayout.HORIZONTAL);
linearSpiCpiCgpa.setWeightSum(4);
for (int i = 0; i < semesterArrayList.get(position).getGetSubjectDetails().size(); i++)
{
linearSub = new LinearLayout(c);
linearSub.setLayoutParams(new TableLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 4));
linearSub.setOrientation(LinearLayout.HORIZONTAL);
TextView subname = new TextView(c);
setSubject(subname);
TextView subcode = new TextView(c);
setSubject(subcode);
TextView subcredit = new TextView(c);
setSubject(subcredit);
TextView subgrade = new TextView(c);
setSubject(subgrade);
subgrade.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
subname.setText(semesterArrayList.get(position).getGetSubjectDetails().get(i).getSubname());
subcode.setText(semesterArrayList.get(position).getGetSubjectDetails().get(i).getSubcode());
subcredit.setText(semesterArrayList.get(position).getGetSubjectDetails().get(i).getSubcredit());
subgrade.setText(semesterArrayList.get(position).getGetSubjectDetails().get(i).getSubgrade());
if (semesterArrayList.get(position).getGetSubjectDetails().get(i).getSubgrade().equals("FF")) {
subgrade.setTextColor(Color.parseColor("#ff0000"));
}
linearSub.addView(subname);
linearSub.addView(subcode);
linearSub.addView(subcredit);
linearSub.addView(subgrade);
linearLayout.addView(linearSub);
}
TextView spi = new TextView(c);
setSpiCpiCgpa(spi);
TextView cpi = new TextView(c);
setSpiCpiCgpa(cpi);
spi.setText(c.getResources().getString(R.string.server_key_result_SPI) + " " + ":" + " " + semesterArrayList.get(position).getSpi());
cpi.setText(c.getResources().getString(R.string.server_key_result_CPI) + " " + ":" + " " + semesterArrayList.get(position).getCpi());
linearSpiCpiCgpa.addView(spi);
linearSpiCpiCgpa.addView(cpi);
linearLayout.addView(linearSpiCpiCgpa);
} else {
linearSpiCpiCgpa = new LinearLayout(c);
linearSpiCpiCgpa.setOrientation(LinearLayout.HORIZONTAL);
linearSpiCpiCgpa.setWeightSum(6);
for (int i = 0; i < semesterArrayList.get(position).getGetSubjectDetails().size(); i++)
{
linearSub = new LinearLayout(c);
linearSub.setOrientation(LinearLayout.HORIZONTAL);
linearSub.setLayoutParams(new TableLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 4));
TextView subname = new TextView(c);
setSubject(subname);
TextView subcode = new TextView(c);
setSubject(subcode);
TextView subcredit = new TextView(c);
setSubject(subcredit);
TextView subgrade = new TextView(c);
setSubject(subgrade);
subname.setText(semesterArrayList.get(position).getGetSubjectDetails().get(i).getSubname());
subcode.setText(semesterArrayList.get(position).getGetSubjectDetails().get(i).getSubcode());
subcredit.setText(semesterArrayList.get(position).getGetSubjectDetails().get(i).getSubcredit());
subgrade.setText(semesterArrayList.get(position).getGetSubjectDetails().get(i).getSubgrade());
linearSub.addView(subname);
linearSub.addView(subcode);
linearSub.addView(subcredit);
linearSub.addView(subgrade);
linearLayout.addView(linearSub);
}
TextView spi = new TextView(c);
setSpiCpiCgpa(spi);
TextView cpi = new TextView(c);
setSpiCpiCgpa(cpi);
TextView cgpi = new TextView(c);
setSpiCpiCgpa(cgpi);
spi.setText(c.getResources().getString(R.string.server_key_result_SPI) + " " + ":" + " " + semesterArrayList.get(position).getSpi());
cpi.setText(c.getResources().getString(R.string.server_key_result_CPI) + " " + ":" + " " + semesterArrayList.get(position).getCpi());
cgpi.setText(c.getResources().getString(R.string.server_key_result_CGPA) + " " + ":" + " " + semesterArrayList.get(position).getCgpi());
linearSpiCpiCgpa.addView(spi);
linearSpiCpiCgpa.addView(cpi);
linearSpiCpiCgpa.addView(cgpi);
linearLayout.addView(linearSpiCpiCgpa);
}
return view;
}
public void setHeader(TextView txtObj, String setText) {
txtObj.setPadding(0, 0, 0, 10);
txtObj.setGravity(Gravity.CENTER_HORIZONTAL);
txtObj.setBackgroundResource(R.drawable.whiteborder);
txtObj.setTextColor(Color.WHITE);
txtObj.setBackgroundColor(Color.parseColor("#80000000"));
txtObj.setTextSize(16);
txtObj.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
txtObj.setLayoutParams(new TableLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 1));
txtObj.setText(setText);
}
public void setSubject(TextView txtObj) {
txtObj.setLayoutParams(new TableLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, 1));
txtObj.setPadding(5, 5, 5, 5);
txtObj.setBackgroundResource(R.drawable.resultborder);
txtObj.setTextColor(Color.WHITE);
txtObj.setGravity(Gravity.CENTER);
}
public void setSpiCpiCgpa(TextView txtObj) {
txtObj.setPadding(5, 5, 5, 5);
txtObj.setGravity(Gravity.CENTER_HORIZONTAL);
txtObj.setTextColor(Color.WHITE);
txtObj.setBackgroundResource(R.drawable.resultborder);
txtObj.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
txtObj.setLayoutParams(new TableLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 2));
}
}
You didn't inflate your View. How do you expect it to not return null?
You should inflate the View in onCreateView() rather than in onPostExecute()
Change it like this.
ShowResultAdapter adapter = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
this.inflaterView = inflater;
this.containerView = container;
context = container.getContext();
newView = inflaterView.inflate(R.layout.your_layout, null);
lv = (ListView) newView.findViewById(R.id.listview); // Define lv at class level
adapter = new ShowResultAdapter(semesterArrayList, getActivity())
lv.setAdapter(adapter);
new StudentResultAsyncTask().execute();
return newView;
}
In your onPostExecute() method do this
protected void onPostExecute(String s)
{
super.onPostExecute(s);
adapter.notifyDataSetChanged();
pDialog.dismiss();
}
Following from the suggestions made by Rohit5k2, alter your getcount() method in your adapter to respond to null data:
#Override
public int getCount() {
if (semesterArrayList == null) {
return 0;
}
return semesterArrayList.size();
}
When you first call setAdapter() on the ListView in Rohit's answer, the data will be null as it is only populated in onPostExecute(). However, if you make the above adjustment, then all will happen is that the list will be empty until the data is populated.