I am trying get the weather details like temp and condition and I am unable to Display them But I am able to see them in my log cat code.
Here is my code follows
cond = (TextView) findViewById(R.id.condDescr);
temp = (TextView) findViewById(R.id.tempText);
temp.setText("HI How are you");
JSONWeatherTask task = new JSONWeatherTask();
task.execute(new String[]{city});
private class JSONWeatherTask extends AsyncTask<String, Void, Weather> {
#Override
protected Weather doInBackground(String... params) {
Weather weather = new Weather();
String data = ( (new WeatherHttpClient()).getWeatherData(params[0]));
try {
weather = JSONWeatherParser.getWeather(data);
// Let's retrieve the icon
//weather.iconData = ( (new WeatherHttpClient()).getImage(weather.currentCondition.getIcon()));
} catch (JSONException e) {
e.printStackTrace();
}
return weather;
}
#Override
protected void onPostExecute(Weather weather) {
super.onPostExecute(weather);
if (weather.iconData != null && weather.iconData.length > 0) {
Bitmap img = BitmapFactory.decodeByteArray(weather.iconData, 0, weather.iconData.length);
//imgView.setImageBitmap(img);
}
String str1 = (weather.currentCondition.getCondition() + "(" + weather.currentCondition.getDescr() + ")");
//temp.setText("" + Math.round((weather.temperature.getTemp() - 273.15)) + "�C");**(I have tried this one too)**
String str2 = ("" + weather.currentCondition.getHumidity() + "%");
Log.w("myApp", str1);
Log.w("mytemp", str2);
cond.setText(str1);
temp.setText(str2);
//temp.setText("" + Math.round((weather.temperature.getTemp() - 273.15)) + "�C");
}
My XML File
<?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" >
<ImageButton
android:id="#+id/but_wifi"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:background="#000000"
android:onClick="onButtonClick"
android:src="#drawable/ic_start_wifi_on" />
<ImageButton
android:id="#+id/but_start_gps"
android:src="#drawable/ic_start_gps_on" />
<View
android:id="#+id/view_mid"
android:layout_width="fill_parent"
android:layout_height="90dp"
android:layout_centerVertical="true" />
<Button
android:id="#+id/but_chooseTrack"
android:textColor="#FFFFFF" />
<Button
android:id="#+id/but_go"
android:layout_width="190dp"
android:text="#string/bt_txt_go"
android:textColor="#FFFFFF" />
<TextView
android:id="#+id/dateText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/but_start_gps"
android:layout_centerHorizontal="true"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/tempText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/dateText"
android:layout_below="#+id/dateText"
android:layout_marginTop="16dp"
android:textAppearance="?android:attr/textAppearanceMedium" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="15dp"
android:layout_toRightOf="#+id/but_wifi"
android:src="#drawable/weather" />
</RelativeLayout>
And I have also tried like manual data set but it is not working for me. I dont know what was my mistake could any one tell me how to solve this.
In order to call the method doInBackground of your ASyncTask, you need to add task.execute(params).
params can be either a String or multiple Strings separated by ,
In your case, you should pass to execute the data needed by the method getWeatherData().
Related
I am creating a GridView to display the data from my database. The Connection and displaying are working perfectly. My question arises when I introduce and If Else statement in my While Loop. Below are my XML files(GridView and CustomGridview respectively):
<GridView
android:id="#+id/gridView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:stretchMode="columnWidth">
</GridView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_marginLeft="5dp"
android:text="ID:"
android:textStyle="bold" />
<TextView
android:id="#+id/ID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="ID"
android:layout_marginLeft="5dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_marginLeft="30dp"
android:text="Company Name:"
android:textStyle="bold" />
<TextView
android:id="#+id/Client"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CompanyName"
android:layout_marginTop="20dp"
android:layout_marginLeft="45dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_marginLeft="145dp"
android:text="Emplyee Name:"
android:textStyle="bold" />
<TextView
android:id="#+id/Employee"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="EmployeeName"
android:layout_marginTop="20dp"
android:layout_marginLeft="145dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="35dp"
android:layout_marginLeft="255dp"
android:textStyle="bold"
android:id="#+id/amountname"
android:text="Amount" />
<TextView
android:id="#+id/Amount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Amount"
android:layout_marginTop="50dp"
android:layout_marginLeft="255dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="35dp"
android:layout_marginLeft="105dp"
android:text="Reason:"
android:textStyle="bold" />
<TextView
android:id="#+id/Reason"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Reason"
android:layout_marginTop="50dp"
android:layout_marginLeft="105dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="35dp"
android:layout_marginLeft="5dp"
android:text="Receipt Date:"
android:textStyle="bold" />
<TextView
android:id="#+id/ReceiptDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ReceiptDate"
android:layout_marginTop="50dp"
android:layout_marginLeft="5dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_marginLeft="255dp"
android:text="Category:"
android:textStyle="bold" />
<TextView
android:id="#+id/Category"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Catergory"
android:layout_marginTop="20dp"
android:layout_marginLeft="255dp" />
The Layout looks like this respectively;
gridView
CustomGridView
and this is my main code:
GridView gridView;
TextView amountno,amountname;
String un, passwords, db, ip;
Connection connect;
ResultSet rs;
#SuppressLint("SetTextI18n")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_data);
ip = "xxx";
un = "xxx";
passwords = "xxx";
db = "xxx";
amountname = (TextView)findViewById(R.id.amountname);
gridView = (GridView) findViewById(R.id.gridView);
CallableStatement callableStatement=null;
amountno=(TextView)findViewById(R.id.Amount);
try{
connect = CONN(un, passwords, db, ip);
String StoredProc = "{call xxx";
callableStatement=connect.prepareCall(StoredProc);
callableStatement.setString(1, MainActivity.usernam);
rs = callableStatement.executeQuery();
List<Map<String,String>> data = new ArrayList<Map<String,String>>();
String eamount="";
while(rs.next()){
Map<String,String> datanum = new HashMap<String, String>();
datanum.put("A", rs.getString("Id"));
datanum.put("B", rs.getString("Client"));
datanum.put("C", rs.getString("Employee"));
if (rs.getString("Amount")=="0.0000"){
eamount=rs.getString("Received");
}else{
eamount=rs.getString("Amount");
}
datanum.put("E", eamount);
datanum.put("F", rs.getString("Reason"));
datanum.put("H", rs.getString("Date"));
datanum.put("K", rs.getString("Category"));
data.add(datanum);
}
String[] from = {"A","B","C","K","H","F","E"};
Log.d("String Value", String.valueOf(amountname));
int[] views = {R.id.ID, R.id.Client, R.id.Employee,R.id.Category,R.id.ReceiptDate,R.id.Reason,R.id.Amount};
Log.d("String Value", String.valueOf(amountname));
final SimpleAdapter ADA = new SimpleAdapter(ViewData.this,data,R.layout.customgrid, from, views);
gridView.setAdapter(ADA);
if(eamount == "Received"){amountname.setText("Received");Log.d("String Value", eamount);}
else if(eamount == "Amount") {amountname.setText("Expenses");Log.d("String Value", eamount);}
}
catch (SQLException e){
e.printStackTrace();
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
#SuppressLint("NewApi")
private Connection CONN(String _user, String _pass, String _DB,
String _server) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection conn = null;
String ConnURL;
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
ConnURL = "jdbc:jtds:sqlserver://" + _server + ";" + "databaseName=" + _DB + ";user=" + _user + ";password=" + _pass + ";";
conn = DriverManager.getConnection(ConnURL);
} catch (Exception e) {
Log.e("ERRO", e.getMessage());
}
return conn;
}
NOW...If you see in my Custom Grid layout I have textview as Amountlabel and it has a respective value from the database below and the IF ELSE statement in my main activity changes the value ( WORKS PERFECTLY)....what I want to change is the Amount Label according to the value it receives from the database ("Receive or Amount")...I want to change the Label to Received Or Expenses accordingly.
I have tried many ways actually, and a lot of time it displayed NULL Point Exception error on the AmountLabel, and I realized that the header of gridview is supposed to be unique, therefore I don't know how to dynamically change the Amount Label with the value the amount(textview below AmountLabel) receives.
NOTE: I have no error in my codes...I just want to dynamically setText the AmountLabel according to the Value the amountValue receives.
THANK YOU ^_^
I have this chat application but because it only has one textview that being appended I don't know how to make it more presentable via designs I learnt the code from the internet and it is the easiest way I can do it can you help me guys?
Here is the code.
private String chat_msg,chat_user_name;
private void append_chat_conversation(DataSnapshot dataSnapshot) {
Iterator i = dataSnapshot.getChildren().iterator();
while (i.hasNext()){
chat_msg = (String) ((DataSnapshot)i.next()).getValue();
chat_user_name = (String) ((DataSnapshot)i.next()).getValue();
chat_conversation.setGravity(Gravity.BOTTOM);
if(chat_user_name.contains(pref.getString("username","").toString())){
chat_conversation.append(chat_user_name + " : " + chat_msg + " \n");
}else {
chat_conversation.append(chat_user_name + " : " + chat_msg + " \n");
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:layout_height="match_parent">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:id="#+id/btn_send"
android:src="#drawable/send"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/msg_input"
android:layout_toLeftOf="#+id/btn_send"
android:layout_toStartOf="#+id/btn_send" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:textSize="15sp"
android:textColor="#000000"
android:scrollbars = "vertical"
android:id="#+id/textView"
android:layout_above="#+id/msg_input" />
</RelativeLayout>
Thank you sirs!!!
Try to add the TextView dynamically for each message.
To add the TextView dynamically, check this sample code
//Get the parent layout
RealtiveLayout relativeLayout = (RealtiveLayout)findViewById(R.id.parent_layout);
//New TextView
TextView textView = new TextView(this);
//Layout Params
textView1.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
textView.setText("Your text");
//Add to the parent
relativelayout.addView(textView1);
Here I'm getting lots of data from web services and I have attached an image of list item too. But my ListView gets stuck or crash when I scroll it. It has lots of data as you can see. I've tried many things but nothing is worth to me.
MainActivity.java
lv = (ListView) findViewById(R.id.script_list);
lv.setScrollingCacheEnabled(false);
lv.setFastScrollEnabled(true);
//AsynTask
public class PostReview extends AsyncTask<Void, Void, String> {
ProgressBar progressBar;
String posted_by = "";
public PostReview(Context con, String item, ProgressBar progressBar) {
this.posted_by = item;
this.progressBar = progressBar;
}
//
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
/*pDialog = new ProgressDialog(ScriptViewClick.this, AlertDialog.THEME_HOLO_DARK);
pDialog.setMessage("Please Wait ..... ");
pDialog.setCancelable(false);
pDialog.show();*/
// progressBar.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(Void... params) {
return getString();
}
private String getString() {
// TODO Auto-generated method stub
String POST_PARAMS = "adivsor_id=" + posted_by;
URL obj = null;
HttpURLConnection con = null;
try {
obj = new URL(Constants.AppBaseUrl + "/advisor_calls/");
String userPassword = "rickmams" + ":" + "advisor11";
String header = "Basic " + new String(android.util.Base64.encode(userPassword.getBytes(), android.util.Base64.NO_WRAP));
con = (HttpURLConnection) obj.openConnection();
con.addRequestProperty("Authorization", header);
con.setRequestMethod("POST");
// For POST only - BEGIN
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
// For POST only - END
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) { // success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
Log.i("TAG21", response.toString());
if (response.toString() != null) {
JSONObject jsonObject;
try {
jsonObject = new JSONObject(response.toString());
JSONArray js = jsonObject.getJSONArray("list");
for (int ii = 0; ii < js.length(); ii++) {
JSONObject c = js.getJSONObject(ii);
EquityDetails allDirectory = new EquityDetails();
allDirectory.setEntry_value(c.getString("entry"));
String value1 = c.getString("entry");
allDirectory.setCall_id(c.getString("call_id"));
String value2 = c.getString("tgt_1");
allDirectory.setSerial_value(c.getString("sl"));
allDirectory.setTg_value1(c.getString("tgt_1"));
allDirectory.setTg_value2(c.getString("tgt_2"));
allDirectory.setMainTitle_value(c.getString("script"));
allDirectory.setMain_subTitle_value(c.getString("exchange"));
allDirectory.setRating_value(c.getString("rating"));
allDirectory.setReview_value(c.getString("review"));
allDirectory.setPosted_by(c.getString("posted_by"));
allDirectory.setImage1(c.getString("advisor_image"));
allDirectory.setImage2(c.getString("script_image"));
allDirectory.setBuy(c.getString("buy_sentiment"));
allDirectory.setSell(c.getString("sell_sentiment"));
allDirectory.setRecommend(c.getString("recommendation"));
allDirectory.setPosted_date(c.getString("posted_date"));
allDirectory.setExpiry_date(c.getString("expiry_date"));
catListDao.add(allDirectory);
}
sca = new ScriptViewAdapter(getApplicationContext(), catListDao);
lv.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
} catch (JSONException e) {
e.printStackTrace();
}
}
return response.toString();
} else {
Log.i("TAG12", "POST request did not work.");
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
lv.setAdapter(sca);
}
}
BaseAdapter of the class
public ScriptViewAdapter(Context com, List<EquityDetails> list) {
this.con = com;
this.items = list;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) con
.getSystemService(con.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.script, null);
holder = new ViewHolder();
holder.tv_rating_title = (TextView) convertView
.findViewById(R.id.script_tv_rating_title);
} else
holder = (ViewHolder) convertView.getTag();
Picasso.with(con)
.load(items.get(position).getImage1())
.into(holder.scriptView);
Picasso.with(con)
.load(items.get(position).getImage2())
.into(holder.advisoryView);
// new DownloadImageTask(holder.advisoryView).execute(items.get(position).getImage1());
// new DownloadImageTask(holder.scriptView).execute(items.get(position).getImage2());
return convertView;
}
XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="#dimen/percentage_text_top_margin"
android:background="#android:color/black"
android:gravity="center"
android:orientation="vertical">
<LinearLayout
android:id="#+id/script_elements_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginBottom="2dp"
android:layout_marginTop="#dimen/percentage_text_top_margin"
android:orientation="horizontal">
<TextView
android:id="#+id/script_tv_element"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="#dimen/et_topPadding"
android:textColor="#color/text_color"
android:textSize="#dimen/home_screen_top_text"
android:textStyle="bold" />
<TextView
android:id="#+id/script_tv_mcx"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/text_color"
android:textSize="#dimen/home_screen_top_text"
android:textStyle="bold" />
<TextView
android:id="#+id/script_tv_year"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/green"
android:textSize="#dimen/home_screen_main_text" />
<TextView
android:id="#+id/script_tv_rating"
android:layout_width="#dimen/rating_number_bg_width"
android:layout_height="#dimen/rating_number_bg_height"
android:layout_marginLeft="#dimen/percentage_text_top_margin"
android:layout_marginRight="#dimen/percentage_text_top_margin"
android:background="#drawable/rating_bg"
android:gravity="center"
android:paddingRight="5dp"
android:text="50"
android:textColor="#FCD730"
android:textSize="#dimen/home_screen_top_text" />
<TextView
android:id="#+id/script_tv_review_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="#dimen/percentage_text_top_margin"
android:text=" Review "
android:textColor="#color/text_color"
android:textSize="#dimen/home_screen_main_text"
android:textStyle="bold" />
<RatingBar
android:id="#+id/script_rating"
android:layout_width="wrap_content"
android:layout_height="#dimen/rating_bar_height"
android:layout_gravity="center"
android:layout_marginLeft="#dimen/percentage_text_top_margin"
android:layout_marginRight="#dimen/percentage_text_top_margin"
android:clickable="false"
android:focusable="false"
android:isIndicator="true"
android:numStars="5"
android:progressDrawable="#drawable/custom_star_rating" />
<TextView
android:id="#+id/script_tv_rating_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Rating"
android:textColor="#color/text_color"
android:textSize="#dimen/home_screen_main_text"
android:textStyle="bold" />
<TextView
android:id="#+id/script_tv_rating_value"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/percentage_text_top_margin"
android:paddingLeft="5dp"
android:text="3"
android:textColor="#color/text_color"
android:textSize="#dimen/home_screen_main_text" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/color_bg_drawer_first">
<ImageView
android:id="#+id/script_iv_logo"
android:layout_width="#dimen/home_screen_image_width"
android:layout_height="#dimen/home_screen_image_height"
android:layout_alignParentLeft="true"
android:layout_marginRight="5dp"
android:background="#drawable/script_img"
android:scaleType="fitXY" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toLeftOf="#+id/script_layout_company_images"
android:layout_toRightOf="#+id/script_iv_logo"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_marginTop="5dp"
android:orientation="horizontal"
android:weightSum="2">
<TextView
android:id="#+id/tv_entry"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/entry"
android:textColor="#color/green"
android:textSize="#dimen/home_screen_main_text"
android:textStyle="bold" />
<TextView
android:id="#+id/script_tv_entry_value"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="2dp"
android:layout_weight="1"
android:text="105.35"
android:textColor="#color/text_color"
android:textSize="#dimen/home_screen_main_text"
android:textStyle="bold" />
<View
android:layout_width="#dimen/view_line_width"
android:layout_height="#dimen/view_line_height"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:background="#color/text_color"
android:visibility="gone" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="2">
<TextView
android:id="#+id/tv_serial_line"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/serial"
android:textColor="#color/green"
android:textSize="#dimen/home_screen_main_text"
android:textStyle="bold" />
<TextView
android:id="#+id/script_tv_serial_line_value"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="2dp"
android:layout_weight="1"
android:text="452.00"
android:textColor="#color/text_color"
android:textSize="#dimen/home_screen_main_text"
android:textStyle="bold" />
<View
android:layout_width="#dimen/view_line_width"
android:layout_height="#dimen/view_line_height"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:background="#color/text_color"
android:visibility="gone" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/tv_tgt"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/tgt"
android:textColor="#color/green"
android:textSize="#dimen/home_screen_main_text"
android:textStyle="bold" />
<TextView
android:id="#+id/script_tv_tgt_value"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="2dp"
android:layout_weight="1"
android:text="104"
android:textColor="#color/text_color"
android:textSize="#dimen/home_screen_main_text"
android:textStyle="bold" />
</LinearLayout>
<TextView
android:id="#+id/script_tv_sentimenst"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="#dimen/edittext_side_margin"
android:text="#string/sentiments"
android:textColor="#color/text_color"
android:textSize="#dimen/home_screen_main_text"
android:textStyle="bold"
android:visibility="gone" />
</LinearLayout>
<LinearLayout
android:id="#+id/script_layout_company_images"
android:layout_width="wrap_content"
android:layout_height="#dimen/home_screen_image_small_height"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:orientation="horizontal"
android:weightSum="2">
<TextView
android:id="#+id/script_iv_icon_sell"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#ff1919"
android:gravity="center"
android:inputType="textCapCharacters"
android:text="recommedn"
android:textColor="#FFF"
android:textSize="#dimen/home_screen_main_text"
android:textStyle="bold" />
<ImageView
android:id="#+id/script_iv_icon_company"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#drawable/small_script"
android:scaleType="fitXY" />
</LinearLayout>
</RelativeLayout>
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginTop="2dp"
android:background="#color/color_bg_drawer_first" />
</LinearLayout>
The stacktrace when app crashes on scroll is
12-12 13:15:58.188 9104-9104/com.package E/filemap: mmap(0,154425) failed: Out of memory
12-12 13:15:58.188 9104-9104/com.package E/InputEventReceiver: Exception dispatching input event.
12-12 13:15:58.188 9104-9104/com.package E/MessageQueue-JNI: Exception in MessageQueue callback: handleReceiveCallback
12-12 13:15:58.218 9104-9104/com.package E/MessageQueue-JNI: java.lang.RuntimeException: native typeface cannot be made
at android.graphics.Typeface.<init>(Typeface.java:334)
at android.graphics.Typeface.createFromAsset(Typeface.java:308)
at com.package.adapters.ScriptViewAdapter.getView(ScriptViewAdapter.java:116)
at android.widget.AbsListView.obtainView(AbsListView.java:2712)
at android.widget.ListView.makeAndAddView(ListView.java:1811)
at android.widget.ListView.fillDown(ListView.java:697)
at android.widget.ListView.fillGap(ListView.java:661)
at android.widget.AbsListView.trackMotionScroll(AbsListView.java:6686)
at android.widget.AbsListView.scrollIfNeeded(AbsListView.java:3920)
at android.widget.AbsListView.onTouchMove(AbsListView.java:4772)
at android.widget.AbsListView.onTouchEvent(AbsListView.java:4600)
at android.view.View.dispatchTouchEvent(View.java:8135)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2416)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2140)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2422)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2155)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2422)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2155)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2422)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2155)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2422)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2155)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2422)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2155)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2422)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2155)
at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2295)
at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1622)
at android.app.Activity.dispatchTouchEvent(Activity.java:2565)
at android.support.v7.internal.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:60)
at android.support.v7.internal.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:60)
at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2243)
at android.view.View.dispatchPointerEvent(View.java:8343)
at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:4767)
at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4633)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4191)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4245)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4214)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4325)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4222)
at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:4382)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4191)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4245)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4214)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4222)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4191)
at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:6556)
at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:6473)
at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:6444)
at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:6409)
at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:6636)
at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:185)
at android.os.MessageQueue.nativePollOnce(Native Method)
at android.os.MessageQueue.next(MessageQue
Note: The size of images are 128X66 and 259X194 pixels.
Accordingly to the code you posted here:
Move all the setTypeFace into the if guard. It is a pretty expensive call and you don't need to do it continuously during the scroll.
Avoid to instantiate SimpleDateFormat every time getView is called. It would better to provide the date in the dataset already in the correct format
Declare the ViewHolder as static: public static class ViewHolder
Make sure the image size is not bigger and should be render fine.
Second, Do not load complete list in one go. Everybody prefer to read make 10 records and load on demand if needed more.
Its a list view and you may load while scrolling.
I always strongly recommended that follow some standards which makes your application faster.
I want some help with putting data from multiple text files into one table shown on an activity.
The text file has a value on each line.
I want these strings to be shown on one column, in a table, where each column shows another text files data of similar format.
I want something like this to be shown:
The code im currently using shows one text file in a textview, how can i manipulate the code to make what i need possible?
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.stats);
File sdCard = Environment.getExternalStorageDirectory();
String path = sdCard.getAbsolutePath() + "/SO/";
File file = new File(path + "cheststats.txt");
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
}
catch (IOException e) {
}
TextView tv = (TextView)findViewById(R.id.tv);
tv.setText(text);
}
}
This is not a good question, because all trivial information that you need for doing this are on Android Developers. But anyway, I hope following steps help you:
1) Create stats.xml layout for stats table:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/tableStats"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Stats"
android:gravity="center"
android:id="#+id/textView4" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="Text File 1 Data"
android:id="#+id/textView1" />
<TextView
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="Text File 2 Data"
android:id="#+id/textView2" />
<TextView
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="Text File 3 Data"
android:id="#+id/textView3" />
</TableRow>
</TableLayout>
2) Create stats_row.xml layout for stats table rows:
<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/textView1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center_vertical|end" />
<TextView
android:id="#+id/textView2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center_vertical|end" />
<TextView
android:id="#+id/textView3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center_vertical|end" />
</TableRow>
3) Next, create function for reading file:
private List<String> readFileData(String filePath) {
List<String> values = new ArrayList<>();
try {
BufferedReader fileBufferedReader = new BufferedReader(new FileReader(new File(filePath)));
String value;
while ((value = fileBufferedReader.readLine()) != null) {
values.add(value);
}
fileBufferedReader.close();
} catch (IOException ignore) {
}
return values;
}
4) Create function for filling stats row view:
private void fillView(View view, String dataset1Value, String dataset2Value, String dataset3Value) {
TextView textView1 = (TextView) view.findViewById(R.id.textView1);
TextView textView2 = (TextView) view.findViewById(R.id.textView2);
TextView textView3 = (TextView) view.findViewById(R.id.textView3);
textView1.setText(dataset1Value);
textView2.setText(dataset2Value);
textView3.setText(dataset3Value);
}
5) Finally your onCreate function should be like this:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.stats);
TableLayout tableStats = (TableLayout) findViewById(R.id.tableStats);
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/SO/";
List<String> data1 = readFileData(path + "file1.txt");
List<String> data2 = readFileData(path + "file2.txt");
List<String> data3 = readFileData(path + "file3.txt");
int maxDataSetSize = Math.max(data1.size(), Math.max(data2.size(), data3.size()));
for (int i = 0; i < maxDataSetSize; i++) {
String dataset1Value = data1.size() > i ? data1.get(i) : null;
String dataset2Value = data2.size() > i ? data2.get(i) : null;
String dataset3Value = data3.size() > i ? data3.get(i) : null;
View statsRowview = getLayoutInflater().inflate(R.layout.stats_row, null);
fillView(statsRowview, dataset1Value, dataset2Value, dataset3Value);
tableStats.addView(statsRowview);
}
}
I'm not sure that it will work at the first attempt. I have not tested.
In my project, im going to make a multiple choice type question. I can select the questions and answer from mysql, however, i cant do the "matching" of the answer between input answer and the data from mysql. I tried some solutions but they doesnt work as well. I need a big help on it. Below are my codes.
the java class that make multiple choice
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.normalmode);
new DataAsyncTask().execute();
}
public void onClick(View v){
inputtext = ((Button) v).getText().toString();
tv3 = (TextView)findViewById(R.id.textView3);
tv3.setText(inputtext);
if(inputtext == tv2.getText().toString()){
playerscore +=5;
} else {
playerscore +=1;
}
score.setText("Scores : " + playerscore);
new DataAsyncTask().execute();
}
class DataAsyncTask extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... param) {
String result = DBConnector.executeQuery("SELECT * FROM questions ORDER BY RAND( ) LIMIT 1");
return result;
}
#Override
protected void onPostExecute(String result) {
question = (TextView)findViewById(R.id.textView_question);
fchoice = (Button)findViewById(R.id.Btn_choice1);
schoice = (Button)findViewById(R.id.Btn_choice2);
tchoice = (Button)findViewById(R.id.Btn_choice3);
tv2 = (TextView)findViewById(R.id.textView2);
score = (TextView)findViewById(R.id.textView_score);
try {
JSONArray jsonArray = new JSONArray(result);
JSONObject jsonData = jsonArray.getJSONObject(0);
question.setText(jsonData.getString("q_desc"));
fchoice.setText(jsonData.getString("fchoice"));
schoice.setText(jsonData.getString("schoice"));
tchoice.setText(jsonData.getString("tchoice"));
ans = jsonData.getString("q_ans");
tv2.setText(ans);
} catch(Exception e) {
Log.e("log_tag", e.toString());
}
}
}
}
three buttons are sharing same onClick in xml file by using
android:onClick="onClick"
the current problem i faced is that it always return "false" no matter i pressed which button. also, is there any way to store/pass "previous" async task data?
I have tried using internal storage but it doesnt work as well
EDIT:
my xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.95" >
<TextView
android:id="#+id/textView_score"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/player_score" />
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.95" >
<TextView
android:id="#+id/textView_question"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="#string/string_question"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Button
android:id="#+id/Btn_choice3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:text="#string/third_choice"
android:onClick="onClick" />
<Button
android:id="#+id/Btn_choice2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/Btn_submit"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:text="#string/second_choice"
android:onClick="onClick" />
<Button
android:id="#+id/Btn_choice1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/Btn_choice2"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:text="#string/first_choice"
android:onClick="onClick" />
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="TextView" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/textView1"
android:text="TextView" />
</RelativeLayout>
</LinearLayout
textview2 and textview3 are used to test my output and display them as text
try this if(inputtext.equals(tv2.getText().toString())) instead of if(inputtext == tv2.getText().toString())
becasue the == operator checks to see if the two strings are exactly the same object.
The .equals() method will check if the two strings have the same value.