Display data in internal storage in a vertical list - android

I am creating an app whereby I store input from edittext and spinner into internal storage. I have used MODE_APPEND so that information stored is not overridden. However it is stored horizontally despite me changing the XML orientation to vertical. How do I overcome that problem?
Portion of MainActivity:
public void Save (View view){
// add-write text into file
// add-write text into file
try {
FileOutputStream fileout=openFileOutput("mytextfile.txt", MODE_PRIVATE | MODE_APPEND);
OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
outputWriter.write(edDate.getText().toString());
outputWriter.close();
//display file saved message
Toast.makeText(getBaseContext(), "File saved successfully!",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
try {
FileOutputStream fileout=openFileOutput("mytextfile2.txt", MODE_PRIVATE | MODE_APPEND);
OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
outputWriter.write(spinner.getSelectedItem().toString());
outputWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
}
RecordDisplay.xml
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".recordsdisplay"
android:orientation="vertical">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:text="Date:"
android:textColor="#000000"
android:textSize="15sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/textViewDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="11dp"
android:layout_marginStart="11dp"
android:layout_marginTop="16dp"
android:textColor="#000000"
android:textSize="15sp"
android:visibility="visible"
app:layout_constraintStart_toEndOf="#+id/textView"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:text="Results:"
android:textColor="#000000"
android:textSize="15sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView" />
<TextView
android:id="#+id/textViewResults"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="11dp"
android:layout_marginStart="11dp"
android:textColor="#000"
android:textSize="15sp"
android:visibility="visible"
app:layout_constraintBaseline_toBaselineOf="#+id/textView3"
app:layout_constraintStart_toEndOf="#+id/textView3" />
RecordDisplay.java
TextView date,Results;
FileInputStream fileInputStream;
static final int READ_BLOCK_SIZE = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recordsdisplay);
date = (TextView) findViewById(R.id.textViewDate);
Results = (TextView) findViewById(R.id.textViewResults);
try {
FileInputStream fileIn=openFileInput("mytextfile.txt");
InputStreamReader InputRead= new InputStreamReader(fileIn);
char[] inputBuffer= new char[READ_BLOCK_SIZE];
String s="";
int charRead;
while ((charRead=InputRead.read(inputBuffer))>0) {
// char to string conversion
String readstring=String.copyValueOf(inputBuffer,0,charRead);
s +=readstring;
}
InputRead.close();
date.setText("Date:" +s);
} catch (Exception e) {
e.printStackTrace();
}
try {
FileInputStream fileIn=openFileInput("mytextfile2.txt");
InputStreamReader InputRead= new InputStreamReader(fileIn);
char[] inputBuffer= new char[READ_BLOCK_SIZE];
String b="";
int charRead;
while ((charRead=InputRead.read(inputBuffer))>0) {
// char to string conversion
String readstring=String.copyValueOf(inputBuffer,0,charRead);
b +=readstring;
}
InputRead.close();
Results.setText("Results:" + b);
} catch (Exception e) {
e.printStackTrace();
}
}
}
enter image description here

You can change ConstraintLayout to LinearLayout. This has the limitation that your XML file must define the exact number of rows when you make the app. If the user can add data and as many rows as she wishes, you should use ListView or RecyclerView instead. For other layout options check out https://developer.android.com/guide/topics/ui/declaring-layout.

Related

How to Display Images from Assets - Image Name from CursorAdapter?

have db with _id,hName,lName,detail,images
images stored in assets
images name in db (SQLite)
list layout without images working fine, but with images layout display's on names not images (no error in logcat)
wanted to bind CursorAdpater with `ImageView'
public void bindView(View view, Context context, Cursor cursor) {
TextView hName = view.findViewById(R.id.hName);
hName.setText(cursor.getString(cursor.getColumnIndex("hName")));
TextView lName = view.findViewById(R.id.lName);
lName.setText(cursor.getString(cursor.getColumnIndex("lName")));
ImageView image = view.findViewById(R.id.image);
InputStream is = null;
try {
is = context.getAssets().open("birds/" + cursor.getColumnIndex("images"));
} catch (IOException e) {
e.printStackTrace();
}
Bitmap bitmap = BitmapFactory.decodeStream(is);
image.setImageBitmap(bitmap);
}
XML file:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/image"
android:scaleType="fitCenter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:padding="24dp"
/>
<TextView
android:id="#+id/hName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/image"
android:layout_marginLeft="21dp"
android:layout_marginStart="10dp"
android:layout_toEndOf="#+id/image"
android:layout_toRightOf="#+id/image"
android:text="Name"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="#+id/lName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/image"
android:layout_alignLeft="#+id/hName"
android:layout_alignStart="#+id/hName"
android:textSize="16sp"
android:text="About" />
check the image extension is used in database
then try this
try {
is = context.getAssets().open("birds/" + cursor.getColumnIndex("images"));
Drawable d = Drawable.createFromStream(is, null);
image.setImageDrawable(d);
} catch (IOException e) {
e.printStackTrace();
}

Dynamically Change the Customgridview's textview according to the data displayed in the Gridview

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 ^_^

Saving EditText to External Storage and Intent in single button

I want to try to save multiple EditText input to a txt file. I also want the button to intent to another activity. I've try to implement the code but my apps crash when i click the button.
This is my code.
MainActivity.Java:
public class MainActivity extends AppCompatActivity {
EditText name, numbTent, pangkat, date, time, penyelia, pegawai;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (EditText) findViewById(R.id.name);
numbTent = (EditText) findViewById(R.id.numbTent);
pangkat = (EditText) findViewById(R.id.pangkat);
date = (EditText) findViewById(R.id.date);
time = (EditText) findViewById(R.id.time);
penyelia = (EditText) findViewById(R.id.penyelia);
pegawai = (EditText) findViewById(R.id.pegawai);
}
public void SaveInfo(View v) {
String state;
state = Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED.equals(state))
{
File Root = Environment.getExternalStorageDirectory();
File Dir = new File(Root.getAbsolutePath()+"/Semak Operasi Mampatan SRC");
if(Dir.exists())
{
Dir.mkdir();
}
File file = new File(Dir,"AttendantInfo.txt");
String Info1 = name.getText().toString();
String Info2 = numbTent.getText().toString();
String Info3 = pangkat.getText().toString();
String Info4 = date.getText().toString();
String Info5 = time.getText().toString();
String Info6 = penyelia.getText().toString();
String Info7 = pegawai.getText().toString();
try {
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(Info1.getBytes());
fileOutputStream.write(Info2.getBytes());
fileOutputStream.write(Info3.getBytes());
fileOutputStream.write(Info4.getBytes());
fileOutputStream.write(Info5.getBytes());
fileOutputStream.write(Info6.getBytes());
fileOutputStream.write(Info7.getBytes());
fileOutputStream.close();
name.setText("");
numbTent.setText("");
pangkat.setText("");
date.setText("");
time.setText("");
penyelia.setText("");
pegawai.setText("");
Toast.makeText(getApplicationContext(),"Info Saved",Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
else
{
Toast.makeText(getApplicationContext(),"Storage not found",Toast.LENGTH_LONG).show();
}
}
Intent i=new Intent(MainActivity.this,ChecklistType.class);
startActivity(i);
}
activitymain.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.hp.semakoperasimampatansrc.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/title"
android:gravity="center"
android:textSize="26sp"
android:textStyle="bold"
android:id="#+id/title"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:id="#+id/name"
android:hint="#string/nama"
android:layout_marginTop="30dp"
android:layout_below="#+id/title"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="text"
android:id="#+id/pangkat"
android:layout_below="#+id/numbTent"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:hint="#string/pangkat" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:id="#+id/penyelia"
android:layout_below="#+id/date"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:hint="#string/penyelia" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:id="#+id/pegawai"
android:layout_below="#+id/penyelia"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:hint="#string/pegawai" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:id="#+id/numbTent"
android:hint="#string/NumTent"
android:layout_below="#+id/name"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="time"
android:ems="10"
android:id="#+id/editText"
android:hint="#string/time"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="datetime"
android:id="#+id/date"
android:hint="#string/date"
android:layout_below="#+id/pangkat"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_toLeftOf="#+id/editText"
android:layout_toStartOf="#+id/editText" />
<Button
android:id="#+id/title_submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/title_submit"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginRight="10dp"
android:layout_marginEnd="10dp"
android:layout_marginBottom="10dp"
android:onClick="SaveInfo"/>
Perhaps this block is wrong :
if(Dir.exists())
{
Dir.mkdir();
}
What you want is if the directory doesn't exist,make it.So when you new .txt file ,it crashes.
if(!Dir.exists())
{
Dir.mkdir();
}
On Android 6.0 and above, the WRITE_EXTERNAL_STORAGE needs to be requested to the user. So you need to check if your application has the permission at startup to avoid your app crash. Something like:
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
Log.v(TAG,"Permission is granted");
//File write logic here
return true;
}
And if not, then you can request for the permissiong using:
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);
This will show a permission request dialog to the user and the user can decide whether or not to allow your application to have the permission.
You can perform desired actions depending upon the result of the permission request in the following function.
#Override
public void onRequestPermissionsResult(int requestCode, String [] permissions, int [] grantResults) {
switch (requestCode) {
case REQUEST_CODE: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted. Write file logic
} else {
// permission denied
}
return;
}
}
}

How to Remove TextView BackGround from listview if value is null?

I am making simple offline chat app, till now every thing is working fine but i want to remove the background of textview if value is null. Chat is having simple left right combination.
protected void showList(){
try {
JSONObject jsonObj = new JSONObject(myJSON);
peoples = jsonObj.getJSONArray(TAG_RESULTS);
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
HashMap<String,String> persons = new HashMap<String,String>();
id = c.getString("sender_id");
ids = c.getString("rec_id");
if(id.equals(session_id)&&ids.equals("admin")) {
ss = c.getString("messages");
persons.put(TAG_MESSAGE, ss);
persons.put("usern", username + ":");
personList.add(persons);
}
if(id.equals("admin")&&ids.equals(session_id)) {
tt = c.getString("messages");
persons.put(TAG_ID, tt);
persons.put("admin","Admin:");
personList.add(persons);
}
adapter = new SimpleAdapter(
Messages.this, personList,
R.layout.activity_message,
new String[]{"admin",TAG_ID, "usern", TAG_MESSAGE },
new int[]{R.id.admin, R.id.id,R.id.name, R.id.messag});
list.setAdapter(adapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
InputStream inputStream = null;
String result = null;
try {
String postReceiverUrl = "http://piresearch.in/gpsapp/emp_message.php";
//"http://progresscard.progresscard.in/progress_card/messages/get_messages.php";
// HttpClient
HttpClient httpClient = new DefaultHttpClient();
// post header
HttpPost httpPost = new HttpPost(postReceiverUrl);
// add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("user_id", session_id));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
inputStream = resEntity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
Log.i("tagconvertstr", "[" + result + "]");
System.out.println(e);
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON = result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
activity_message.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="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp" >
<TextView
android:textSize="20dp"
android:gravity="start"
android:textAlignment="textStart"
android:id="#+id/admin"
android:text="admin"
android:textColor="#fff"
android:layout_gravity="left"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:paddingBottom="2dip"
android:paddingTop="6dip" />
<TextView
android:layout_below="#id/admin"
android:textSize="20dp"
android:gravity="start"
android:textAlignment="textStart"
android:id="#+id/id"
android:background="#drawable/mystyle"
android:textColor="#000"
android:layout_gravity="left"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:paddingTop="6dip" />
<TextView
android:id="#+id/name"
android:textSize="20dp"
android:textColor="#fff"
android:layout_gravity="right"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:paddingBottom="2dip"
android:paddingTop="6dip"/>
<TextView
android:background="#drawable/mystyle"
android:layout_below="#id/name"
android:id="#+id/messag"
android:textSize="20dp"
android:textColor="#000"
android:layout_gravity="right"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:paddingTop="6dip"/>
</LinearLayout>
activity_list.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:background="#drawable/main_background"
android:orientation="vertical">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="30dp"
android:text="Your Messages"
android:textAlignment="center"
android:background="#dedb36"/>
<ListView
android:id="#+id/listView"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#null"
android:divider="#null"
android:transcriptMode="alwaysScroll"
android:stackFromBottom="true"/>
<LinearLayout
android:gravity="bottom"
android:id="#+id/llMsgCompose"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#color/white"
android:orientation="horizontal"
android:weightSum="3">
<EditText
android:id="#+id/inputMsg"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="2"
android:background="#color/bg_msg_input"
android:textColor="#color/text_msg_input"
android:paddingLeft="6dp"
android:paddingRight="6dp"/>
<Button
android:id="#+id/btnSend"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#color/bg_btn_join"
android:textColor="#fff"
android:text="Send" />
</LinearLayout>
</LinearLayout>
The simplest solution would be to do not add that item in the list which is having a null value.
You can simply hide it when it has no value.
textView.setVisibility(View.INVISIBLE);
Although not adding the item is probably the best practice as others have stated. I think this should do the trick you're looking for.
textView.setBackgroundColor(android.R.color.transparent);
Here you're setting the background to transparent, hence removing any background that exists.
textView.setBackgroundColor(
isEmpty(textView.getText().toString()) ? android.R.color.transparent: R.color.yourColor
);
which sets the textviewBackground to trasparent if text is empty. else it will show the your color, By using conditional operator.

Android read from multiple text files and show in table view

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.

Categories

Resources