I am learning android application development online I have created a project using guideline from http://www.edumobile.org/android/android-beginner-tutorials/ftp-message-viewer-in-android/ but getting error call "ftp_host cannot be resolved or not a field" and "ftp_message_result cannot be resolved or not a field".
My Layout file includes following
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView android:text="#string/ftp_server_prompt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<EditText android:id="#+id/ftp_host"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textUri">
<requestFocus></requestFocus>
</EditText>
</LinearLayout>
<Button android:text="#string/ftp_button_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="showMessage"/>
<ScrollView android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:id="#+id/ftp_message_result"
android:textSize="#dimen/ftp_message_size"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</ScrollView>
</LinearLayout>
and my MainActivity file looks like below
import java.io.BufferedReader;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import android.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
private EditText mFtpHost;
private TextView mFtpMessageResult;
private static final int FTP_PORT = 8080;
/** Initializes the app when it is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_item);
mFtpHost = (EditText)findViewById(R.id.ftp_host);
mFtpMessageResult = (TextView)findViewById(R.id.ftp_message_result);
}
public void showMessage(View clickedButton) {
String host = mFtpHost.getText().toString();
try {
Socket socket = new Socket();//(host, FTP_PORT);
BufferedReader in = SocketUtils.getReader(socket);
List<String> results = new ArrayList<String>();
String line = in.readLine();
results.add(line);
if (line.startsWith("220-")) {
while((line = in.readLine()) != null) {
results.add(line);
if ((line.equals("220") || line.startsWith("220 "))) {
break;
}
}
}
String output = makeOutputString(results);
mFtpMessageResult.setText(output);
socket.close();
} catch (Exception e) {
mFtpMessageResult.setText("Unknown host: " + host);
e.printStackTrace(); // View this in DDMS window
}
}
private String makeOutputString(List<String> results) {
StringBuilder output = new StringBuilder();
for (String s: results) {
output.append(s + "\n");
}
return(output.toString());
}
}
Proof if your layout file is really called activity_list_item. If it isn't you have to change
setContentView(R.layout.activity_list_item);
,in your onCreate()-Method, to:
setContentView(R.layout.'THE NAME OF THE LAYOUT');
Related
i making a gridview to open pdf files from asset
i have used download directory to show pdf file but now i want to use asset
And i am changing main activity and pdf activity to fragments
Guys help me with asset folder
sample code
CustomAdaptor.java
package com.tutorials.hp.gridviewpdf;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class CustomAdapter extends BaseAdapter {
Context c;
ArrayList<PDFDoc> pdfDocs;
public CustomAdapter(Context c, ArrayList<PDFDoc> pdfDocs) {
this.c = c;
this.pdfDocs = pdfDocs;
}
#Override
public int getCount() {
return pdfDocs.size();
}
#Override
public Object getItem(int i) {
return pdfDocs.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if(view==null)
{
//INFLATE CUSTOM LAYOUT
view= LayoutInflater.from(c).inflate(R.layout.model,viewGroup,false);
}
final PDFDoc pdfDoc= (PDFDoc) this.getItem(i);
TextView nameTxt= (TextView) view.findViewById(R.id.nameTxt);
ImageView img= (ImageView) view.findViewById(R.id.pdfImage);
//BIND DATA
nameTxt.setText(pdfDoc.getName());
img.setImageResource(R.drawable.pdf_icon);
//VIEW ITEM CLICK
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openPDFView(pdfDoc.getPath());
}
});
return view;
}
//OPEN PDF VIEW
private void openPDFView(String path)
{
Intent i=new Intent(c,PDF_Activity.class);
i.putExtra("PATH",path);
c.startActivity(i);
}
}
PDF_Activity.java
i will be using fragment instead activity
package com.tutorials.hp.gridviewpdf;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
import com.github.barteksc.pdfviewer.PDFView;
//import com.github.barteksc.pdfviewer.ScrollBar;
import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener;
import java.io.File;
public class PDF_Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pdf);
//PDFVIEW SHALL DISPLAY OUR PDFS
PDFView pdfView= (PDFView) findViewById(R.id.pdfView);
//SCROLLBAR TO ENABLE SCROLLING
// ScrollBar scrollBar = (ScrollBar) findViewById(R.id.scrollBar);
// pdfView.setScrollBar(scrollBar);
//VERTICAL SCROLLING
// scrollBar.setHorizontal(false);
//SACRIFICE MEMORY FOR QUALITY
//pdfView.useBestQuality(true)
//UNPACK OUR DATA FROM INTENT
Intent i=this.getIntent();
String path=i.getExtras().getString("PATH");
//GET THE PDF FILE
File file=new File(path);
if(file.canRead())
{
//LOAD IT
pdfView.fromFile(file).defaultPage(1).onLoad(new OnLoadCompleteListener() {
#Override
public void loadComplete(int nbPages) {
Toast.makeText(PDF_Activity.this, String.valueOf(nbPages), Toast.LENGTH_LONG).show();
}
}).load();
}
}
}
PDFDoc.java
package com.tutorials.hp.gridviewpdf;
import android.net.Uri;
public class PDFDoc {
String name,path;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
}
MainActivity.java
i will be using fragment instead activity
i need asset folder to show there pdf files
package com.tutorials.hp.gridviewpdf;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.GridView;
import java.io.File;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final GridView gv= (GridView) findViewById(R.id.gv);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
gv.setAdapter(new CustomAdapter(MainActivity.this,getPDFs()));
}
});
}
private ArrayList<PDFDoc> getPDFs()
{
ArrayList<PDFDoc> pdfDocs=new ArrayList<>();
//TARGET FOLDER
File downloadsFolder= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
PDFDoc pdfDoc;
if(downloadsFolder.exists())
{
//GET ALL FILES IN DOWNLOAD FOLDER
File[] files=downloadsFolder.listFiles();
//LOOP THRU THOSE FILES GETTING NAME AND URI
for (int i=0;i<files.length;i++)
{
File file=files[i];
if(file.getPath().endsWith("pdf"))
{
pdfDoc=new PDFDoc();
pdfDoc.setName(file.getName());
pdfDoc.setPath(file.getAbsolutePath());
pdfDocs.add(pdfDoc);
}
}
}
return pdfDocs;
}
}
layout
activity_main.xml
i will be using fragment instead activity
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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"
android:fitsSystemWindows="true"
tools:context="com.tutorials.hp.gridviewpdf.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
activity_pdf.xml
i will be using fragment instead activity
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#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.tutorials.hp.gridviewpdf.PDF_Activity">
<com.github.barteksc.pdfviewer.PDFView
android:id="#+id/pdfView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_toLeftOf="#+id/scrollBar"/>
<com.github.barteksc.pdfviewer.ScrollBar
android:id="#+id/scrollBar"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.tutorials.hp.gridviewpdf.MainActivity"
tools:showIn="#layout/activity_main">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="PDF VIEWER" />
<GridView
android:id="#+id/gv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:numColumns="2" />
</LinearLayout>
</RelativeLayout>
model.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_margin="10dp"
card_view:cardCornerRadius="5dp"
card_view:cardElevation="5dp"
android:layout_height="200dp">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/pdfImage"
android:src="#drawable/pdf_icon"
android:layout_width="150dp"
android:layout_height="wrap_content" />
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Name"
android:id="#+id/nameTxt"
android:padding="10dp"
android:textColor="#color/colorAccent"
android:textStyle="bold"
android:layout_alignParentLeft="true"
/>
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
Include this permission in manifest if you are storing pdf in external storage.
Use Asset folder like this
AssetManager assetManager = getAssets();
File file = new File(getFilesDir(), "xyz.pdf");
in = assetManager.open("xyz.pdf");
out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
You can open it as an input stream like this from a fragment
reader = new BufferedReader(new InputStreamReader(getActivity().getAssets().open(myfile.pdf))
You don't need permisssions as you're accessing your app's internal files but putting pdf into assets can increase the weight of the app , be careful
and then you can save it as string like that
private StringBuilder text = new StringBuilder();
String mLine;
while ((mLine = reader.readLine()) != null) {
text.append(mLine);
text.append('\n');
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}
I'm new to Android and Rest Template.I have developed a android
screen and display JSON data using Rest Template GET method on my
screen.My next step is to update some fields like edit name and add
missing things and save back to the rest Template.
public class MyPreferences extends AppCompatActivity {
TextView tv;
private Listcp = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_preferences);
Resources resources = getResources();
Log.d("Consumer pojo", "onCreate:");
new HttpRequestTask().execute();
}
private class HttpRequestTask extends AsyncTask<Void, Void, ConsumerProfile>{
#Override
protected ConsumerProfile doInBackground(Void... params) {
try {
final String url = "http://192.168.1.213:9001/consumer/local/"+LoginFragment.CONSUMEROBJECT.getId();
RestTemplate restTemplate = new RestTemplate();
ConsumerProfile cp = restTemplate.getForObject(url, ConsumerProfile.class);
return cp;
}catch (Exception e){
Log.e("MainActivity", e.getMessage(),e );
}
return null;
}
#Override
protected void onPostExecute(ConsumerProfile cp){
super.onPostExecute(cp);
Log.d("cppppppppppppppppppppp", "onPostExecute: " + cp.getId());
TextView fname=(TextView)findViewById(R.id.editfname);
TextView mname=(TextView)findViewById(R.id.editmname);
TextView lname=(TextView)findViewById(R.id.editlname);
TextView nname=(TextView)findViewById(R.id.editnname);
TextView dob=(TextView)findViewById(R.id.editdob);
TextView status=(TextView)findViewById(R.id.editstatus);
TextView homeAddress=(TextView)findViewById(R.id.edithomeAddr);
TextView workAddress=(TextView)findViewById(R.id.editworkAddr);
TextView income=(TextView)findViewById(R.id.editincome);
fname.setText(cp.getFirstName());
mname.setText(cp.getMiddleName());
lname.setText(cp.getLastName());
nname.setText(cp.getNickName());
dob.setText(cp.getDob());
status.setText(cp.getStatus());
homeAddress.setText(cp.getHomeAddress());
workAddress.setText(cp.getWorkAddress());
income.setText(cp.getIncome());
}
}This Screen is for Get Method
This is what I did Up to Now.
This code is for Get method.
It'll display The screen like in image.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"><![CDATA[
android:id="#+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
]]>
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/scrollView2" >
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"> <TextView
android:layout_width="wrap_content"
android:scrollbars="vertical"
android:layout_height="wrap_content"
android:text="firstName"/>
<EditText
android:id="#+id/editfname"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="middleName"/>
<EditText
android:id="#+id/editmname"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="lastName"/>
<EditText
android:id="#+id/editlname"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="nickName"/>
<EditText
android:id="#+id/editnname"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="dob"/>
<EditText
android:id="#+id/editdob"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="status"/>
<EditText
android:id="#+id/editstatus"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="homeAddress"/>
<EditText
android:id="#+id/edithomeAddr"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="workAddress"/>
<EditText
android:id="#+id/editworkAddr"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="income"/>
<EditText
android:id="#+id/editincome"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:scrollbars="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Update Preferences"
android:id="#+id/button"
android:layout_gravity="center_horizontal" />
</LinearLayout>
</ScrollView>
</LinearLayout>
This is my layout.
Actually what I'm trying to do is Get User Information and Edit Information and save back to the same end point.
When the user select Update button Then it I'll Display the Updated Screen.
Any help Appreciated.
Anyone Provide code for that.
Thankful to them.
package com.nusecond.suredeal.app.suredeal.activity;
import android.content.Intent;
import android.content.res.Resources;
import android.net.http.HttpResponseCache;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.nusecond.suredeal.app.R;
import com.nusecond.suredeal.app.suredeal.pojo.Consumer;
import com.nusecond.suredeal.app.suredeal.pojo.ConsumerProfile;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
public class MyPreferences extends AppCompatActivity {
Button button;
TextView tv;
TextView fname,mname,lname,nname,dob,status,homeAddress,workAddress,income;
private String FName,MName,LName,NName,Dob,Status,HomeAddress,WorkAddress,Income;
private List<ConsumerProfile>cp = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_preferences);
Resources resources = getResources();
Log.d("Consumer pojo", "onCreate:");
new HttpRequestTask().execute();
addListenerOnButton();
}
private void addListenerOnButton() {
//final String url = "http://192.168.1.213:9001/consumer/local/"+LoginFragment.CONSUMEROBJECT.getId();
Button button=(Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FName=fname.getText().toString();
MName=mname.getText().toString();
LName=lname.getText().toString();
NName=nname.getText().toString();
Dob=dob.getText().toString();
Status=status.getText().toString();
HomeAddress=homeAddress.getText().toString();
WorkAddress=workAddress.getText().toString();
new HttpUpdateTask().execute();
// Toast.makeText(addListenerOnButton(),"UpdatedSuccessfully",Toast.LENGTH_LONG).show();
Intent intent=new Intent(MyPreferences.this,MainActivity.class);
startActivity(intent);
}
});
}
private class HttpRequestTask extends AsyncTask<Void, Void, ConsumerProfile>{
#Override
protected ConsumerProfile doInBackground(Void... params) {
try {
final String url = "http://192.168.1.213:9001/consumer/local/"+LoginFragment.CONSUMEROBJECT.getId();
RestTemplate restTemplate = new RestTemplate();
ConsumerProfile cp = restTemplate.getForObject(url, ConsumerProfile.class);
return cp;
}catch (Exception e){
Log.e("MainActivity", e.getMessage(),e );
}
return null;
}
#Override
protected void onPostExecute(ConsumerProfile cp){
super.onPostExecute(cp);
Log.d("cppppppppppppppppppppp", "onPostExecute: " + cp.getId());
fname=(TextView)findViewById(R.id.editfname);
mname=(TextView)findViewById(R.id.editmname);
lname=(TextView)findViewById(R.id.editlname);
nname=(TextView)findViewById(R.id.editnname);
dob=(TextView)findViewById(R.id.editdob);
status=(TextView)findViewById(R.id.editstatus);
homeAddress=(TextView)findViewById(R.id.edithomeAddr);
workAddress=(TextView)findViewById(R.id.editworkAddr);
income=(TextView)findViewById(R.id.editincome);
fname.setText(cp.getFirstName());
mname.setText(cp.getMiddleName());
lname.setText(cp.getLastName());
nname.setText(cp.getNickName());
dob.setText(cp.getDob());
status.setText(cp.getStatus());
homeAddress.setText(cp.getHomeAddress());
workAddress.setText(cp.getWorkAddress());
income.setText(cp.getIncome());
//FName=fname.getText().toString();
}
}
private class HttpUpdateTask extends AsyncTask<Void,Void,ConsumerProfile>{
#Override
protected ConsumerProfile doInBackground(Void... params) {
try {
final String url = "http://192.168.1.213:9001/consumer/local/" + LoginFragment.CONSUMEROBJECT.getId();
RestTemplate restTemplate = new RestTemplate();
ConsumerProfile consumerProfile = new ConsumerProfile();
// String m=FName;
consumerProfile.setFirstName(FName);
fname=(TextView)findViewById(R.id.editfname);
Log.d(" llllllllllllll", "doInBackground: " + FName);
consumerProfile.setMiddleName(MName);
consumerProfile.setLastName(LName);
consumerProfile.setNickName(NName);
consumerProfile.setDob(Dob);
consumerProfile.setStatus(Status);
consumerProfile.setHomeAddress(HomeAddress);
consumerProfile.setWorkAddress(WorkAddress);
consumerProfile.setDob(Income);
restTemplate.put(url,consumerProfile);
Log.d("ettttttttttttttt", "doInBackground: ");
return consumerProfile;
}catch (Exception e){
Log.e( "consumer", e.getMessage(),e);
}
return null;
}
}
}
I made a client program on my android and when I receive long messages it doesn't show the whole msg. I have tried to add android:orientation="horizontal" to the XML file but that didn't fix anything.
package com.example.marcus.chatclient1;
import android.app.Activity;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.Adapter;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Array;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Arrays;
import static android.R.layout.list_content;
public class chat extends Activity {
Handler hanGET;
String string = "test";
String name;
EditText msgBox;
Button sButton;
ListView lv;
TextView errorT;
ObjectOutputStream o;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
final Button join = (Button) findViewById(R.id.joinButton);
final EditText nameT = (EditText) findViewById(R.id.editTextName);
msgBox = (EditText)findViewById(R.id.msgField);
sButton = (Button)findViewById(R.id.sendButton);
errorT = (TextView) findViewById(R.id.errorText);
lv = (ListView)findViewById(R.id.ChatList);
msgBox.setVisibility(View.INVISIBLE);
sButton.setVisibility(View.INVISIBLE);
lv.setVisibility(View.INVISIBLE);
join.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
name = nameT.getText().toString();
join.setVisibility(View.INVISIBLE);
nameT.setVisibility(View.INVISIBLE);
lv.setVisibility(View.VISIBLE);
msgBox.setVisibility(View.VISIBLE);
sButton.setVisibility(View.VISIBLE);
new Thread(new ClientThread()).start();
final ArrayList<String> ar = new ArrayList<String>();
final ArrayAdapter ad = new ArrayAdapter(getApplicationContext(),android.R.layout.simple_gallery_item, ar);
lv.setBackgroundColor(Color.BLACK);
lv.setAdapter(ad);
hanGET = new Handler(){
public void handleMessage(Message message) {
ar.add(string);
ad.notifyDataSetChanged();
}
};
}
});
}
class ClientThread implements Runnable {
public void run() {
Message message;
Socket s;
try {
s = new Socket("192.168.0.15", 55555);
o = new ObjectOutputStream(s.getOutputStream());
o.writeObject(name);
ObjectInputStream in = new ObjectInputStream(s.getInputStream());
sButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
String m = msgBox.getText().toString();
o.writeObject(m);
} catch (IOException e) {
e.printStackTrace();
}
}
});
while(true) {
try {
string = in.readObject().toString();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
message = Message.obtain();
hanGET.sendMessage(message);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
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.marcus.chatclient1.chat">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Join"
android:id="#+id/joinButton"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:text="Name"
android:ems="10"
android:id="#+id/editTextName"
android:layout_marginBottom="31dp"
android:layout_above="#+id/joinButton"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:id="#+id/errorText"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/ChatList"
android:layout_alignParentTop="true"
android:clickable="false"
android:layout_alignBottom="#+id/joinButton"
android:choiceMode="none"
tools:listitem="#android:layout/simple_gallery_item"
tools:listfooter="#layout/activity_chat"
android:visibility="visible"
android:layout_centerHorizontal="true"
android:headerDividersEnabled="false" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textMultiLine"
android:ems="10"
android:id="#+id/msgField"
android:layout_below="#+id/ChatList"
android:layout_toRightOf="#+id/errorText"
android:layout_toEndOf="#+id/errorText"
android:visibility="visible" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send"
android:id="#+id/sendButton"
android:layout_alignBottom="#+id/msgField"
android:layout_toRightOf="#+id/joinButton"
android:layout_toEndOf="#+id/joinButton"
android:visibility="visible" />
</RelativeLayout>
A ListView must have the layout_height attribute not setted to wrap_content. A ListView content height is dynamic, since you don't always have the same number of cells. Thus, you need to match the parent size or have a fixed height.
I am doing Android Application for shopping. I need to display products as grid as well as list like this:
https://lh6.ggpht.com/Ly21pAbBRIxAzHn2R119a37NexxtjG5RkQJV8vv0IoCywzksIhKNSCkzWikbUnH8bGY=h900-rw
I don't know how to do this using image button or tabs. Can I change layout of the fragment at runtime? Or I have use 2 different fragments? Please help me.
You have multiple options:
Use RecyclerView
Have two different fragments
Have two different layouts
Use a Framelayout and switch visibility of sub views
Use a ViewFlipper or ViewSwitcher
Why use two layouts when you can simply use RecyclerView and use an imagebutton to handle the clicks and when clicked you can use something like this
// The number of Columns
mLayoutManager = new GridLayoutManager(this, 2);
mRecyclerView.setLayoutManager(mLayoutManager);
and when the listbutton is clicked you can use something like this:
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
I'm not sure whether it would work or not, its just an example,If you want to learn more about implementing girds and lists using RecyclerView and CardView, check out these tutorials I made:
Custom Android lists with CardView and RecyclerView
Custom Android Grids with Images and Texts using RecyclerView
Just look at this:
xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="horizontal" >
<LinearLayout
android:id="#+id/tlist"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center" >
<TextView
android:id="#+id/textview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ListView"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#color/white" />
</LinearLayout>
<LinearLayout
android:id="#+id/tgrid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center" >
<TextView
android:id="#+id/textview2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="GridView"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#color/white" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.1" >
<LinearLayout
android:id="#+id/gridid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:visibility="gone" >
<GridView
android:id="#+id/gridView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:horizontalSpacing="5dp"
android:numColumns="2"
android:verticalSpacing="5dp" >
</GridView>
</LinearLayout>
<LinearLayout
android:id="#+id/listid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:dividerHeight="10sp" >
</ListView>
</LinearLayout>
</LinearLayout>
</LinearLayout>
MainActivity.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.Adapter.FriendAdapter;
import com.example.bean.FriendBean;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Color;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
private ListView mlist;
private GridView mgrid;
private ArrayList<FriendBean> arr = new ArrayList<FriendBean>();
private FriendAdapter friendAdapter1, friendAdapter2;
private int slist = R.layout.list;
private int sgrid = R.layout.grid;
private TextView list, grid;
LinearLayout listid, gridid, tlist, tgrid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mlist = (ListView) findViewById(R.id.listView1);
mgrid = (GridView) findViewById(R.id.gridView1);
list = (TextView) findViewById(R.id.textview1);
grid = (TextView) findViewById(R.id.textview2);
listid = (LinearLayout) findViewById(R.id.listid);
gridid = (LinearLayout) findViewById(R.id.gridid);
tlist = (LinearLayout) findViewById(R.id.tlist);
tgrid = (LinearLayout) findViewById(R.id.tgrid);
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(getAssets().open(
"listgrid.json")));
String temp;
while ((temp = br.readLine()) != null)
sb.append(temp);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally {
try {
br.close(); // stop reading
} catch (IOException e) {
e.printStackTrace();
}
}
String myjsonstring = sb.toString();
try {
JSONObject obj = new JSONObject(myjsonstring);
JSONArray jsonarray = obj.getJSONArray("lg");
Log.e("Length", "" + jsonarray.length());
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonObj = jsonarray.getJSONObject(i);
String num = jsonObj.getString("number");
String url = jsonObj.getString("image_url");
FriendBean bean = new FriendBean(url, num);
arr.add(bean);
Log.e("image_url", url);
Log.e("number", num);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
tlist.setBackgroundColor(Color.RED);
tgrid.setBackgroundColor(Color.BLACK);
friendAdapter1 = new FriendAdapter(MainActivity.this, slist, arr);
mlist.setAdapter(friendAdapter1);
/*****JUST LOOK AT THIS****/
list.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
gridid.setVisibility(View.GONE);
listid.setVisibility(View.VISIBLE);
tlist.setBackgroundColor(Color.RED);
tgrid.setBackgroundColor(Color.BLACK);
friendAdapter1 = new FriendAdapter(MainActivity.this, slist, arr);
mlist.setAdapter(friendAdapter1);
}
});
/*****JUST LOOK AT THIS****/
grid.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
gridid.setVisibility(View.VISIBLE);
listid.setVisibility(View.GONE);
tgrid.setBackgroundColor(Color.RED);
tlist.setBackgroundColor(Color.BLACK);
friendAdapter2 = new FriendAdapter(MainActivity.this, sgrid, arr);
mgrid.setAdapter(friendAdapter2);
}
});
}
}
I want to put a text in a TextView sequentially, with a known time between characters, from a written text in an EditText
That is the solution I made:
I wrote two ArrayList charged from an EditText, the first one with Characters from the EditText , the second one with Integers for determine the time between characters.
Then I parse the ArrayLists, times load of the time integers are done sequentially, but not the characters, the TextViews are drawn only when the cycle ends.
My code
The MainActivity:
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView showCharacter;
private TextView showAppendCharacter;
private EditText incomingText;
private Button readTextEdit;
private ArrayList<CharSequence> toText = new ArrayList<CharSequence>();
private ArrayList<Integer> timePlay = new ArrayList<Integer>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showCharacter = (TextView) findViewById(R.id.showCharacterTextView);
showAppendCharacter = (TextView) findViewById(R.id.showAppendCharacterTextView);
incomingText = (EditText) findViewById(R.id.incomingEditText);
readTextEdit = (Button) findViewById(R.id.readTextButton);
readTextEdit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
toText.clear();
timePlay.clear();
showAppendCharacter.setText("");
String text = incomingText.getText().toString();
for (int base = 0; base < text.length(); base++) {
if (String.valueOf(text.charAt(base)).equals("a")) {
toText.add(("a"));
timePlay.add(500);
} else if (String.valueOf(text.charAt(base)).equals("b")) {
toText.add(("b"));
timePlay.add(650);
} else if (String.valueOf(text.charAt(base)).equals("c")) {
toText.add(("c"));
timePlay.add(800);
} else {
toText.add(("_"));
timePlay.add(1000);
}
}
for (int pos = 0; pos < toText.size(); pos++) {
try {
Thread.sleep(timePlay.get(pos));
showCharacter.setText((String) toText.get(pos));
showAppendCharacter.append((String) toText.get(pos));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
}
}
The activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:id="#+id/showCharacterTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/showCharacterTextView"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/showAppendCharacterTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/showAppendCharactersTextView"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="#+id/incomingEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/incomingTextEditText"
android:inputType="text" >
<requestFocus />
</EditText>
<Button
android:id="#+id/readTextButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/readButton" />
The strings.xml:
<?xml version="1.0" encoding="utf-8"?>
<string name="app_name">texto Desde ArrayList</string>
<string name="action_settings">Settings</string>
<string name="showCharacterTextView">Show last Character</string>
<string name="showAppendCharactersTextView">Show append Characters</string>
<string name="incomingTextEditText">Incoming text</string>
<string name="readButton">Read text</string>
Try something like this... You can get rid of the Arraylists. Remember a String is basically an array of chars. create a custom text view that implements runnable so the work that your trying to do with the text is not done on the main thread.
package com.example.stackquestion;
import java.util.ArrayList;
import android.content.Context;
import android.graphics.Color;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.widget.TextView;
public class CustomTextView extends TextView implements Runnable {
String text = null;
int i = 0;
int length = 0;
String currentText = "";
public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
reset();
}
#Override
public void run() {
if (i < length) {
currentText = currentText + text.charAt(i);
setText(currentText);
if (text.charAt(i) == 'a') {
postDelayed(this, 500);
} else if (text.charAt(i) == 'b') {
postDelayed(this, 650);
} else if (text.charAt(i) == 'c') {
postDelayed(this, 800);
} else if (text.charAt(i) == '_') {
postDelayed(this, 1000);
} else
postDelayed(this, 1);
i++;
}
}
public void setString(String text) {
this.text = text;
this.length = text.length();
}
public void reset() {
currentText = "";
text = null;
i = 0;
setText("");
}
}
Here is the main Activity
package com.example.stackquestion;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView showCharacter;
private CustomTextView showAppendCharacter;
private EditText incomingText;
private Button readTextEdit;
private ArrayList<CharSequence> toText = new ArrayList<CharSequence>();
private ArrayList<Integer> timePlay = new ArrayList<Integer>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showCharacter = (TextView) findViewById(R.id.showCharacterTextView);
showAppendCharacter = (CustomTextView) findViewById(R.id.showAppendCharacterTextView);
incomingText = (EditText) findViewById(R.id.incomingEditText);
readTextEdit = (Button) findViewById(R.id.readTextButton);
readTextEdit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (v.getId() == R.id.readTextButton)
showAppendCharacter.reset();
showAppendCharacter
.setString(incomingText.getText().toString());
showAppendCharacter.run();
}
});
}
}
woops. I forgot to give you the Layout. But looks like you got it. Just change the type of textview to a fully qualified CustomTextView. Here was mine.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:id="#+id/showCharacterTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/showCharacterTextView"
android:textAppearance="?android:attr/textAppearanceLarge" />
<com.example.stackquestion.CustomTextView
android:id="#+id/showAppendCharacterTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/showAppendCharactersTextView"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="#+id/incomingEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/incomingTextEditText"
android:inputType="text" >
<requestFocus />
</EditText>
<Button
android:id="#+id/readTextButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/readButton" />
</LinearLayout>