How to pass Context into public class with public static String method - android

I have a public class with one public static String method. I have to getString() and I know that before that I have to extract String ressource and pass Context and I dont know how to pass it .
Another class uses public static String method
Code example:
public class StringUtil {
public static String sumUp(int nr1, int nr2) {
int sum = nr1 + nr2;
String result;
//all what is in ""
result =.getString(R.string.result) + sum;
return result;
}
}
ButtonListener class uses public static String method. Code:
public class ButtonListener extends MainActivity implements View.OnClickListener {
MainActivity activity;
EditText et1;
EditText et2;
public ButtonListener(MainActivity activity) {
this.activity = activity;
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.sum:
et1 = (EditText) activity.findViewById(R.id.nr1_edit_text);
et2 = (EditText)activity.findViewById(R.id.nr2_edit_text);
String nr1In = et1.getText().toString();
String nr2In = et1.getText().toString();
int nr1 = Integer.parseInt(nr1In);
int nr2 = Integer.parseInt(nr2In);
Intent intent = new Intent(activity, IntentActivity.class);
intent.putExtra("result", StringUtil.sumUp(nr1, nr2));
activity.startActivity(intent);
break;
}
}
}
IntentActivity class ´getIntent´ Code:
public class IntentActivity extends MainActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
TextView textView = (TextView)findViewById(R.id.result);
Intent intent = getIntent();
String fResult = intent.getStringExtra("result");
textView.setText(fResult);
}
}
And MainActivity Code:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButtonListener bl = new ButtonListener(this);
Button sumUp= (Button)findViewById(R.id.sum_button);
sumUp.setOnClickListener(bl);
}
}

public class StringUtil {
public static String sumUp(int nr1, int nr2, Context context){
int sum = nr1 +nr2;
String result;
result = context.getString(R.string.result) + sum;
return result;
}
}
And use it like:
StringUtil.sumUp(1,2, this); // from Activity
StringUtil.sumUp(1,2, getContext()); // from Fragment

You have 2 ways:
1.to pass it as a parameter for your method:
public static String sumUp(int nr1, int nr2 ,Context context){
int sum = nr1 +nr2;
String result;
//all what is in ""
result = .getString(R.string.result) + sum;
return result;
}
2.to add context to the class constructor and then you can use it inside your method:
public class StringUtil {
Context context;
public void StringUtil (Context context){
this.context = context;
}
public static String sumUp(int nr1, int nr2){
int sum = nr1 +nr2;
String result;
//all what is in ""
result = .getString(R.string.result) + sum;
return result;
}
}

Replace your StringUtil class with this.
public class StringUtil {
public static String sumUp(Context mContext, int nr1, int nr2){
int sum = nr1 +nr2;
String result;
//all what is in ""
result = mContext.getString(R.string.result) + sum;
return result;
}
}
Edit
And call this method from your ButtonListener activity.
intent.putExtra("result", StringUtil.sumUp(ButtonListener.this, nr1, nr2));

Related

Read Data from SQLite Databse in Another Activity using ID

I have already Read Data from Sqlite database in recyclerview
But when user click next_button it fetch more data from same row using BANK_ID
In First Activity I have read some data from sqlite database in recyclerView And When user click next_button its fetch more data from sqlite database using same row I've already pass BANK_ID which is autoIncrement
Here is my code...
DataModel Class
public class DataModel {
public String BANK_ID;
public String id;
public String farmer_insure_name;
public String farmer_bank_hypo;
public String farmer_name;
public String village;
public String taluka;
public String district;
public String tagging_date;
public String tag_no;
public String animal_species;
public String animal_breed;
public String body_color;
public String shape_right;
public String shape_left;
public String tail_switch;
public String other_marks;
public String prag_status;
public String lactations;
public String milk_qty;
public String sum_insured;
public String tag_photo;
public String head_photo;
public String left_photo;
public String right_photo;
public String farmer_photo;
public String getBANK_ID() {
return BANK_ID;
}
public void setBANK_ID(String BANK_ID) {
this.BANK_ID = BANK_ID;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFarmer_insure_name() {
return farmer_insure_name;
}
public void setFarmer_insure_name(String farmer_insure_name) {
this.farmer_insure_name = farmer_insure_name;
}
public String getFarmer_bank_hypo() {
return farmer_bank_hypo;
}
public void setFarmer_bank_hypo(String farmer_bank_hypo) {
this.farmer_bank_hypo = farmer_bank_hypo;
}
public String getFarmer_name() {
return farmer_name;
}
public void setFarmer_name(String farmer_name) {
this.farmer_name = farmer_name;
}
public String getVillage() {
return village;
}
public void setVillage(String village) {
this.village = village;
}
public String getTaluka() {
return taluka;
}
public void setTaluka(String taluka) {
this.taluka = taluka;
}
public String getDistrict() {
return district;
}
public void setDistrict(String district) {
this.district = district;
}
public String getTagging_date() {
return tagging_date;
}
public void setTagging_date(String tagging_date) {
this.tagging_date = tagging_date;
}
public String getTag_no() {
return tag_no;
}
public void setTag_no(String tag_no) {
this.tag_no = tag_no;
}
public String getAnimal_species() {
return animal_species;
}
public void setAnimal_species(String animal_species) {
this.animal_species = animal_species;
}
public String getAnimal_breed() {
return animal_breed;
}
public void setAnimal_breed(String animal_breed) {
this.animal_breed = animal_breed;
}
public String getBody_color() {
return body_color;
}
public void setBody_color(String body_color) {
this.body_color = body_color;
}
public String getShape_right() {
return shape_right;
}
public void setShape_right(String shape_right) {
this.shape_right = shape_right;
}
public String getShape_left() {
return shape_left;
}
public void setShape_left(String shape_left) {
this.shape_left = shape_left;
}
public String getTail_switch() {
return tail_switch;
}
public void setTail_switch(String tail_switch) {
this.tail_switch = tail_switch;
}
public String getOther_marks() {
return other_marks;
}
public void setOther_marks(String other_marks) {
this.other_marks = other_marks;
}
public String getPrag_status() {
return prag_status;
}
public void setPrag_status(String prag_status) {
this.prag_status = prag_status;
}
public String getLactations() {
return lactations;
}
public void setLactations(String lactations) {
this.lactations = lactations;
}
public String getMilk_qty() {
return milk_qty;
}
public void setMilk_qty(String milk_qty) {
this.milk_qty = milk_qty;
}
public String getSum_insured() {
return sum_insured;
}
public void setSum_insured(String sum_insured) {
this.sum_insured = sum_insured;
}
public String getTag_photo() {
return tag_photo;
}
public void setTag_photo(String tag_photo) {
this.tag_photo = tag_photo;
}
public String getHead_photo() {
return head_photo;
}
public void setHead_photo(String head_photo) {
this.head_photo = head_photo;
}
public String getLeft_photo() {
return left_photo;
}
public void setLeft_photo(String left_photo) {
this.left_photo = left_photo;
}
public String getRight_photo() {
return right_photo;
}
public void setRight_photo(String right_photo) {
this.right_photo = right_photo;
}
public String getFarmer_photo() {
return farmer_photo;
}
public void setFarmer_photo(String farmer_photo) {
this.farmer_photo = farmer_photo;
}
}
DatabaseHelper Class
public class DatabaseHelper extends SQLiteOpenHelper {
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
public static final String DATABASE_NAME = "SNVINSURANCE.db";
public static final String TABLE_NAME_IMAGES = "images_table";
private static final int DATABASE_VERSION = 1;
private static final String IMAGES_TABLE = "ImagesTable";
public static final String COLUMN_ID = "ID";
public static final String BANK_COLUMN = "BANK_NAME";
public static final String INSURED_COLUMN = "INSURED_NAME";
public static final String BNAKHYPO_COLUMN = "BANKHYPO_NAME";
public static final String COLUMN_STATUS = "status";
public static final String FARMERNAME_ID = "ID";
public static final String SNV_ID = "SNV";
public static final String FARMERNAME_COLUMN = "FARMER_NAME";
public static final String VILLAGE_COLUMN = "VILLAGE";
public static final String TALUKA_COLUMN = "TALUKA";
public static final String DISTRICT_COLUMN = "DISTRICT";
public static final String TAGGING_DATE_COLUMN = "TAGGING_DATE";
public static final String ANIMAL_ID = "ID";
public static final String TAG_COLUMN = "TAG";
public static final String ANIMAL_SPECIES_COLUMN = "ANIMAL_SPECIES";
public static final String ANIMAL_BREED_COLUMN = "ANIMAL_BREED";
public static final String ANIMAL_BODY_COLOR_COLUMN = "ANIMAL_BODY_COLOR";
public static final String ANIMAL_SHAPE_RIGHT_COLUMN = "ANIMAL_SHAPE_RIGHT";
public static final String ANIMAL_SHAPE_LEFT_COLUMN = "ANIMAL_SHAPE_LEFT";
public static final String ANIMAL_SWITCH_OF_TAIL_COLUMN = "ANIMAL_SWITCH_OF_TAIL";
public static final String AGE_COLUMN = "AGE";
public static final String ANIMAL_OTHER_MARKS_COLUMN = "ANIMAL_OTHER_MARKS";
public static final String PRAG_STATUS_COLUMN = "PRAG_STATUS";
public static final String NUMBER_OF_LACTATION_COLUMN = "NUMBER_OF_LACTATION";
public static final String CURRENT_MILK_COLUMN = "CURRENT_MILK";
public static final String SUM_INSURED_COLUMN = "SUM_INSURED";
public static final String TAG_IMAGE_COLUMN = "TAG_IMAGE";
public static final String HEAD_IMAGE_COLUMN = "HEAD_IMAGE";
public static final String LEFT_SIDE_IMAGE_COLUMN = "LEFT_SIDE_IMAGE";
public static final String RIGHT_SIDE_IMAGE_COLUMN = "RIGHT_SIDE_IMAGE";
public static final String TAIL_IMAGE_COLUMN = "TAIL_IMAGE";
public static final String IDPROOF_IMAGE_COLUMN = "IDPROOF_IMAGE";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME_IMAGES + "(BANK_ID INTEGER PRIMARY KEY AUTOINCREMENT,BANK_NAME TEXT,INSURED_NAME TEXT,BANKHYPO_NAME TEXT,FARMER_NAME TEXT,VILLAGE TEXT,TALUKA TEXT,DISTRICT TEXT,TAGGING_DATE DATE, TAG NUMBER,ANIMAL_SPECIES TEXT,ANIMAL_BREED TEXT,ANIMAL_BODY_COLOR TEXT,ANIMAL_SHAPE_RIGHT TEXT,ANIMAL_SHAPE_LEFT TEXT,ANIMAL_SWITCH_OF_TAIL TEXT,AGE NUMBER,ANIMAL_OTHER_MARKS TEXT,PRAG_STATUS TEXT,NUMBER_OF_LACTATION NUMBER,CURRENT_MILK NUMBER,SUM_INSURED NUMBER,TAG_IMAGE BLOB NOT NULL,HEAD_IMAGE BLOB NOT NULL,LEFT_SIDE_IMAGE BLOB NOT NULL,RIGHT_SIDE_IMAGE BLOB NOT NULL,TAIL_IMAGE BLOB NOT NULL,IDPROOF_IMAGE BLOB NOT NULL)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME_IMAGES);
onCreate(db);
}
public boolean insertImage(String bank, String insurename, String bankhypo, String farmername, String village, String taluka, String district, String tagging_date, String tag, String animal_species, String animal_breeds, String animal_body_color, String shape_right, String shape_left, String tail, String age, String marks_other, String prag, String lactation, String current_milk, String sum, byte[] tag_image, byte[] head_image, byte[] left_image, byte[] right_image, byte[] tail_image, byte[] id_proof_image) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(BANK_COLUMN, bank);
contentValues.put(INSURED_COLUMN, insurename);
contentValues.put(BNAKHYPO_COLUMN, bankhypo);
contentValues.put(FARMERNAME_COLUMN, farmername);
contentValues.put(VILLAGE_COLUMN, village);
contentValues.put(TALUKA_COLUMN, taluka);
contentValues.put(DISTRICT_COLUMN, district);
contentValues.put(TAGGING_DATE_COLUMN, tagging_date);
contentValues.put(TAG_COLUMN, tag);
contentValues.put(ANIMAL_SPECIES_COLUMN, animal_species);
contentValues.put(ANIMAL_BREED_COLUMN, animal_breeds);
contentValues.put(ANIMAL_BODY_COLOR_COLUMN, animal_body_color);
contentValues.put(ANIMAL_SHAPE_RIGHT_COLUMN, shape_right);
contentValues.put(ANIMAL_SHAPE_LEFT_COLUMN, shape_left);
contentValues.put(ANIMAL_SWITCH_OF_TAIL_COLUMN, tail);
contentValues.put(AGE_COLUMN, age);
contentValues.put(ANIMAL_OTHER_MARKS_COLUMN, marks_other);
contentValues.put(PRAG_STATUS_COLUMN, prag);
contentValues.put(NUMBER_OF_LACTATION_COLUMN, lactation);
contentValues.put(CURRENT_MILK_COLUMN, current_milk);
contentValues.put(SUM_INSURED_COLUMN, sum);
contentValues.put(TAG_IMAGE_COLUMN, tag_image);
contentValues.put(HEAD_IMAGE_COLUMN, head_image);
contentValues.put(LEFT_SIDE_IMAGE_COLUMN, left_image);
contentValues.put(RIGHT_SIDE_IMAGE_COLUMN, right_image);
contentValues.put(TAIL_IMAGE_COLUMN, tail_image);
contentValues.put(IDPROOF_IMAGE_COLUMN, id_proof_image);
long result = db.insert(TABLE_NAME_IMAGES, null, contentValues);
if (result == -1)
return false;
else
return true;
}
public DatabaseHelper open() throws SQLException {
SQLiteDatabase db = this.getWritableDatabase();
return this;
}
public List<DataModel> getdata() {
// DataModel dataModel = new DataModel();
List<DataModel> data = new ArrayList<>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("select BANK_ID,BANK_NAME,INSURED_NAME,BANKHYPO_NAME,FARMER_NAME,VILLAGE,TALUKA,DISTRICT,TAGGING_DATE from " + TABLE_NAME_IMAGES + " ;", null);
StringBuffer stringBuffer = new StringBuffer();
DataModel dataModel = null;
while (cursor.moveToNext()) {
dataModel = new DataModel();
String BANK_ID = cursor.getString(cursor.getColumnIndexOrThrow("BANK_ID"));
String name = cursor.getString(cursor.getColumnIndexOrThrow("BANK_NAME"));
String country = cursor.getString(cursor.getColumnIndexOrThrow("INSURED_NAME"));
String city = cursor.getString(cursor.getColumnIndexOrThrow("BANKHYPO_NAME"));
String FARMER_NAME = cursor.getString(cursor.getColumnIndexOrThrow("FARMER_NAME"));
String VILLAGE = cursor.getString(cursor.getColumnIndexOrThrow("VILLAGE"));
String TALUKA = cursor.getString(cursor.getColumnIndexOrThrow("TALUKA"));
String DISTRICT = cursor.getString(cursor.getColumnIndexOrThrow("DISTRICT"));
String TAGGING_DATE = cursor.getString(cursor.getColumnIndexOrThrow("TAGGING_DATE"));
dataModel.setBANK_ID(BANK_ID);
dataModel.setId(name);
dataModel.setFarmer_insure_name(city);
dataModel.setFarmer_bank_hypo(country);
dataModel.setFarmer_name(FARMER_NAME);
dataModel.setVillage(VILLAGE);
dataModel.setTaluka(TALUKA);
dataModel.setDistrict(DISTRICT);
dataModel.setTagging_date(TAGGING_DATE);
stringBuffer.append(dataModel);
// stringBuffer.append(dataModel);
data.add(dataModel);
}
for (DataModel mo : data) {
Log.e("Hellomo", "" + mo.getFarmer_insure_name());
}
//
return data;
}
}
First Activity Class
public class SyncAllActivity extends AppCompatActivity {
Cursor model = null;
Cursor mode = null;
MyCustomAdapter adapter = null;
Button show;
DatabaseHelper database;
private RecyclerView recyclerview;
RecycleAdapter recycler;
List<DataModel> datamodel;
private ProgressDialog pdialog;
Context context;
private RecyclerView.LayoutManager mLayoutManager;
private MyCustomAdapter myCustomAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sync_all_activity);
context = this;
datamodel = new ArrayList<DataModel>();
recyclerview = findViewById(R.id.recycle);
database = new DatabaseHelper(SyncAllActivity.this);
datamodel = database.getdata();
recycler = new RecycleAdapter(datamodel);
Log.e("data", "" + datamodel);
LinearLayoutManager layoutManager = new LinearLayoutManager(context);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerview.setLayoutManager(layoutManager);
recyclerview.setHasFixedSize(true);
myCustomAdapter = new MyCustomAdapter(datamodel);
recyclerview.setAdapter(myCustomAdapter);
}
public class MyCustomAdapter extends RecyclerView.Adapter<MyCustomAdapter.MyViewHolder> {
List<DataModel> moviesList;
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView bank_company, insured_name, bank_hypo;
CardView cardView;
MaterialRippleLayout next_button_main_activity;
public MyViewHolder(View view) {
super(view);
context = itemView.getContext();
bank_company = itemView.findViewById(R.id.tvInsuranceList);
insured_name = itemView.findViewById(R.id.tvInsuredName);
bank_hypo = itemView.findViewById(R.id.tvBankHypo);
cardView = itemView.findViewById(R.id.cardViewMain);
next_button_main_activity = itemView.findViewById(R.id.next_button_main_activity);
}
}
public MyCustomAdapter(List<DataModel> moviesList) {
this.moviesList = moviesList;
}
#Override
public MyCustomAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.sam1
, parent, false);
return new MyCustomAdapter.MyViewHolder(itemView);
}
public void clear() {
int size = this.moviesList.size();
if (size > 0) {
for (int i = 0; i < size; i++) {
this.moviesList.remove(0);
}
this.notifyItemRangeRemoved(0, size);
}
}
#Override
public void onBindViewHolder(final MyCustomAdapter.MyViewHolder holder, final int position) {
final DataModel dataModel = moviesList.get(position);
holder.bank_company.setText(dataModel.getId());
holder.insured_name.setText(dataModel.getFarmer_insure_name());
holder.bank_hypo.setText(dataModel.getFarmer_bank_hypo());
holder.cardView.setVisibility(View.VISIBLE);
holder.next_button_main_activity.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(context, SyncFarmerActivity.class);
intent.putExtra("BANK_ID", moviesList.get(position).getBANK_ID() + "");
Log.e("id", moviesList.get(position).getBANK_ID() + "");
startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return moviesList.size();
}
}
}
Second Activity Class
public class SyncFarmerActivity extends AppCompatActivity {
Button show;
DatabaseHelper database;
private RecyclerView recyclerview;
RecycleAdapter recycler;
List<DataModel> datamodel;
String id;
Context context;
private RecyclerView.LayoutManager mLayoutManager;
private MyCustomAdapter myCustomAdapter;
DataModel dataModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sync_farmer);
context = this;
Intent i = getIntent();
id = i.getStringExtra("BANK_ID");
Log.e("BANK_ID", id + "");
datamodel = new ArrayList<DataModel>();
recyclerview = findViewById(R.id.recycle);
database = new DatabaseHelper(SyncFarmerActivity.this);
datamodel = database.getdata();
recycler = new RecycleAdapter(datamodel);
Log.e("HIteshdata", "" + datamodel);
LinearLayoutManager layoutManager = new LinearLayoutManager(context);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerview.setLayoutManager(layoutManager);
recyclerview.setHasFixedSize(true);
myCustomAdapter = new MyCustomAdapter(datamodel);
recyclerview.setAdapter(myCustomAdapter);
}
public class MyCustomAdapter extends RecyclerView.Adapter<MyCustomAdapter.MyViewHolder> {
List<DataModel> moviesList;
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView tvFarmerName, tvCity, tvTaluka, farmer_name, tvDistrict, tvTaggingDate, district, tagging_date;
CardView cardView;
MaterialRippleLayout next_button_main_activity;
public MyViewHolder(View view) {
super(view);
context = itemView.getContext();
tvFarmerName = itemView.findViewById(R.id.tvFarmerName);
tvCity = itemView.findViewById(R.id.tvCity);
tvTaluka = itemView.findViewById(R.id.tvTaluka);
tvDistrict = itemView.findViewById(R.id.tvDistrict);
tvTaggingDate = itemView.findViewById(R.id.tvTaggingDate);
}
}
public MyCustomAdapter(List<DataModel> moviesList) {
this.moviesList = moviesList;
}
#Override
public MyCustomAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.sam
, parent, false);
return new MyCustomAdapter.MyViewHolder(itemView);
}
public void clear() {
int size = this.moviesList.size();
if (size > 0) {
for (int i = 0; i < size; i++) {
this.moviesList.remove(0);
}
this.notifyItemRangeRemoved(0, size);
}
}
#Override
public void onBindViewHolder(MyCustomAdapter.MyViewHolder holder, final int position) {
DataModel dataModel = moviesList.get(position);
holder.tvFarmerName.setText(dataModel.getFarmer_name());
holder.tvCity.setText(dataModel.getVillage());
holder.tvTaluka.setText(dataModel.getTaluka());
holder.tvDistrict.setText(dataModel.getDistrict());
holder.tvTaggingDate.setText(dataModel.getTagging_date());
}
#Override
public int getItemCount() {
return moviesList.size();
}
}
}
Can anyone help me..
Thank You in advance.
You have to create another method in your Database class to select values from specific id that you are passing from first activity like:
DatabaseHelper Class
public List<DataModel> getSpecificData(String id) {
// DataModel dataModel = new DataModel();
List<DataModel> data = new ArrayList<>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("select BANK_ID,BANK_NAME,INSURED_NAME,BANKHYPO_NAME,FARMER_NAME,VILLAGE,TALUKA,DISTRICT,TAGGING_DATE from " + TABLE_NAME_IMAGES + "WHERE BANK_ID = " + id + ";", null);
StringBuffer stringBuffer = new StringBuffer();
DataModel dataModel = null;
while (cursor.moveToNext()) {
//Rest of your code
return data;
}
And use this method in your second activity like
Intent i = getIntent();
id = i.getStringExtra("BANK_ID");
database = new DatabaseHelper(SyncFarmerActivity.this);
datamodel = database.getSpecificData(id);

Update an EditText of an Intent from a variable of an object

I will try to be brief and precise:
I have a user object that contains a chat, and this is updated every time I receive a message:
public class Usuarios implements Serializable {
private static final long serialVersionUID = 1113799434508676095L;
private int id;
private String nombre;
private String ip;
private boolean isSInicial;
//HERE WILL GO THE VARIABLE THAT STORMS THE CHAT, BUT I DO NOT KNOW HOW TO IMPLEMENT IT
public Usuarios(int id, String nombre, String ip, boolean isSInicial){
this.id = id;
this.nombre = nombre;
this.ip = ip;
this.isSInicial = isSInicial;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public boolean isSInicial() {
return isSInicial;
}
public void setSInicial(boolean SInicial) {
isSInicial = SInicial;
}}
I have an activity, that by clicking on a list, loads a new activity for the specific user:
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int pos, long id) {
Usuarios e = (Usuarios) listview.getItemAtPosition(pos);
Intent visorDetalles = new Intent(view.getContext(),Chat.class);
if(Contactos.listaDeContactos.indexOf(e) >= 0) {
visorDetalles.putExtra("indice", Contactos.listaDeContactos.indexOf(e));
startActivity(visorDetalles);
}
else{
Toast.makeText(contexto,"Usuario fuera de linea",Toast.LENGTH_LONG);
}
}
});
I need the EditText that contains the Intent to be updated automatically every time I click on a user of a ListView.
I do not know what kind of variable I should use in the user object and how to implement it.
In your Usuarios class add the variable:
public ArrayList<String> currentChat;
Instead of passing the index, pass the Object himself maybe.
if(Contactos.listaDeContactos.indexOf(e) >= 0) {
visorDetalles.putExtra("usuario",e);
startActivity(visorDetalles);
}
else{
Toast.makeText(contexto,"Usuario fuera de linea",Toast.LENGTH_LONG);
}
And in your onCreate Chat Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
Intent intent = getIntent();
Usuario usuario = (Usuario) intent.getSerializableExtra("usuario");
EditText myEditText = (EditText)findViewById(R.id.myEditText1));
String allChat;
for(String chatLine : usuario.currentChat) {
allChat += chatLine + '\n';
}
myEditText.setText(allChat);
Did I got your problem right ?

How to share a post's content in android?

I have a recycelerview that get JSON data from mySQl database online and I want to have a share button for each post that can share each post's content ,as you see i used "ACTION_SEND" codes but it doesn't share my content and just share the body sentence(the exact sentence that is in sharedBodyText),please tell me how can i share my post?here is my codes:
codes for the page that shows full post:
public class full_post extends AppCompatActivity {
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_full_post);
Intent intent=getIntent();
int id=intent.getIntExtra(koreDatabaseOpenHelper.COL_ID,0);
String title=intent.getStringExtra(koreDatabaseOpenHelper.COL_TITLE);
String content=intent.getStringExtra(koreDatabaseOpenHelper.COL_CONTENT);
String date=intent.getStringExtra(koreDatabaseOpenHelper.COL_DATE);
TextView titleTextView=(TextView)findViewById(R.id.post_title);
TextView contentTextView=(TextView)findViewById(R.id.post_content);
TextView dateTextView=(TextView)findViewById(R.id.post_date);
titleTextView.setText(title);
contentTextView.setText(content);
dateTextView.setText(date);
}
public void shareText(View view) {
Intent intent = new Intent(android.content.Intent.ACTION_SEND);
intent.setType("text/plain");
String shareBodyText =(koreDatabaseOpenHelper.COL_CONTENT) ;
intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject/Title");
intent.putExtra(android.content.Intent.EXTRA_TEXT, shareBodyText);
startActivity(Intent.createChooser(intent, "Choose sharing method"));
}}
codes of my DatabaseHelper :
public class koreDatabaseOpenHelper extends SQLiteOpenHelper {
private static final String TAG = "DatabaseOpenHelper";
private static final String DATABASE_NAME="db_kdramadl";
private static final int DATABASE_VERSION=1;
private static final String POST_TABLE_NAME="tbl_posts";
public static final String COL_ID="col_id";
public static final String COL_TITLE="col_title";
public static final String COL_CONTENT="col_content";
public static final String COL_DATE="col_date";
private static final String SQL_COMMAND_CREATE_POST_TABLE="CREATE TABLE IF NOT EXISTS "+POST_TABLE_NAME+"("+
COL_ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+
COL_TITLE+" TEXT,"+
COL_CONTENT+" TEXT, "+
" INTEGER DEFAULT 0, "+
COL_DATE+" TEXT);";
Context context;
public koreDatabaseOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context=context;
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(SQL_COMMAND_CREATE_POST_TABLE);
}catch (SQLException e){
Log.e(TAG, "onCreate: "+e.toString() );
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public boolean addPost(Post post){
ContentValues cv=new ContentValues();
cv.put(COL_ID,post.getId());
cv.put(COL_TITLE,post.getTitle());
cv.put(COL_CONTENT,post.getContent());
cv.put(COL_DATE,post.getDate());
SQLiteDatabase sqLiteDatabase=this.getWritableDatabase();
long isInserted=sqLiteDatabase.insert(POST_TABLE_NAME,null,cv);
Log.i(TAG, "addPost: "+isInserted);
if (isInserted>0){
return true;
}else{
return false;
}
}
public void addPosts(List<Post> posts){
for (int i = 0; i < posts.size(); i++) {
if (!checkPostExists(posts.get(i).getId())) {
addPost(posts.get(i));
}
}
}
and this is my adapter :
public class PostAdapter extends RecyclerView.Adapter<PostAdapter.PostViewHolder> {
private Context context;
private List<Post> posts;
public PostAdapter (Context context, List<Post> posts){
this.context = context;
this.posts = posts;
}
#Override
public PostViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(context).inflate(R.layout.postha,parent,false);
Typeface morvaridTypeface=Typeface.createFromAsset(context.getAssets(),"fonts/morvarid.ttf");
return new PostViewHolder(view,morvaridTypeface);
}
#Override
public void onBindViewHolder(PostViewHolder holder, int position) {
final Post post=posts.get(position);
holder.title.setText(post.getTitle());
holder.content.setText(post.getContent());
holder.date.setText(post.getDate());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(context,full_post.class);
intent.putExtra(koreDatabaseOpenHelper.COL_ID,post.getId());
intent.putExtra(koreDatabaseOpenHelper.COL_TITLE,post.getTitle());
intent.putExtra(koreDatabaseOpenHelper.COL_CONTENT,post.getContent());
intent.putExtra(koreDatabaseOpenHelper.COL_DATE,post.getDate());
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return posts.size();
}
public class PostViewHolder extends RecyclerView.ViewHolder{
private TextView title;
private TextView content;
private TextView date;
public PostViewHolder(View itemView) {
super(itemView);
title=(TextView)itemView.findViewById(R.id.post_title);
content=(TextView)itemView.findViewById(R.id.post_content);
date=(TextView)itemView.findViewById(R.id.post_date);
}
}}
I have used below code to share post URL.You can use mUrl as your content.
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT,**mUrl**);
startActivity(Intent.createChooser(intent,getString("your apps title")));
mUrl(String) replace with Your post content (String)...
In your full_post.class, receive the extra passed from adapter,then create a button as share and then add this
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent what = new Intent();
what.setAction(Intent.ACTION_SEND);
what.putExtra(Intent.EXTRA_TEXT, "Post Id:" + postId+ "\nPost
Title:" +postTitle);
what.setType("text/plain");
startActivity(Intent.createChooser(what, "Share with"));
}
});
where postId,postTitle are received as axtra from adapter class

I have one issue on ListView

I want to implement refine on my app where the item will come from server but in the below Custom_List class code only one item is coming and another item is shown as null.This is screenshot of items.
On this item I am retrieving id,age,height,communities,caste,occupation,education,income,location,pics.
public class RefineCustomList extends ArrayAdapter<String> {
private NetworkImageView imageView;
private ImageLoader imageLoader;
private final String[] ids;
private String[] ages;
private String[] heights;
public String[] communities;
public String[] castes;
public String[] educations;
public String[] occupations;
public String[] incomes;
public String[] pics;
public String[] locations;
public String[] shortlist;
public String[] expressinterest;
private Activity context;
public RefineCustomList(Activity context, String[] ids, String[] ages, String[] heights, String[] communities, String[] castes,
String[] educations, String[] occupations, String[]incomes, String[]pics, String[] locations,
String[] shortlist, String[] expressinterest) {
super(context, R.layout.list_view_layout,ids);
this.ids = ids;
this.ages = ages;
this.heights = heights;
this.communities = communities;
this.castes = castes;
this.educations = educations;
this.occupations = occupations;
this.incomes = incomes;
this.pics = pics;
this.locations = locations;
this.context = context;
this.shortlist = shortlist;
this.expressinterest = expressinterest;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.refine_custom_list, null, true);
String url1 = "https://www.maangal.com/thumb/thumb_";
String url =url1+pics[position];
imageView = (NetworkImageView) listViewItem.findViewById(R.id.offer_image);
imageLoader = CustomVolleyRequest.getInstance(this.getContext()).getImageLoader();
imageLoader.get(url, ImageLoader.getImageListener(imageView,R.drawable.image,android.R.drawable.ic_dialog_alert));
imageView.setImageUrl(url,imageLoader);
TextView textViewId = (TextView) listViewItem.findViewById(R.id.textViewId);
TextView textViewName = (TextView) listViewItem.findViewById(R.id.textViewName);
textViewId.setText(ids[position]);
textViewName.setText( ages[position]+" years"+" , "+heights[position]+" cm"+", "+communities[position]+" : "+castes[position]+" , "+educations[position]+" , "+occupations[position]+" , "+incomes[position]+", "+locations[position]);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(v.getContext(), BlankActivity.class);
Toast.makeText(getContext(), ids[position], Toast.LENGTH_LONG).show();
i.putExtra("id", ids[position]);
v.getContext().startActivity(i);
}
});
Button btnSort =(Button) listViewItem.findViewById(R.id.btnshort);
btnSort.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(),"Shortlisted",Toast.LENGTH_LONG).show();
}
});
Button btnChat =(Button) listViewItem.findViewById(R.id.btnchat);
btnChat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(),"Chatting",Toast.LENGTH_LONG).show();
}
});
Button declineButton = (Button)listViewItem.findViewById(R.id.declineButton);
declineButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(),"Decline",Toast.LENGTH_LONG).show();
}
});
return listViewItem;
}
}
This is the parsing code
public class RefineActivity extends FragmentActivity {
SessionManager session;
String email;
public String JSON_URL;
private ListView listView;
Button rfb;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.refine_activity);
// Session class instance
session = new SessionManager(this);
// get user data from session
HashMap<String, String> user = session.getUserDetails();
email = user.get(SessionManager.KEY_EMAIL);
Log.e("email==========>", email);
//JSON_URL = "http://10.0.2.2/xp/ei_sent_pending.php?matri_id="+email;
listView = (ListView) findViewById(R.id.listView);
rfb = (Button) findViewById(R.id.refineBtn);
rfb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fragmentManager = getFragmentManager();
RefineFragment ls_fragment = new RefineFragment();
ls_fragment.show(fragmentManager, "simple fragment");
}
});
Intent intent = getIntent();
final String response = getIntent().getExtras().getString("res");
Log.e("responde rfi", response);
showJSON(response);
}
protected void showJSON(String json) {
ParseJSON pj = new ParseJSON(json);
pj.parseJSON();
RefineCustomList cl = new RefineCustomList(this, ParseJSON.ids, ParseJSON.ages, ParseJSON.heights, ParseJSON.communities, ParseJSON.castes, ParseJSON.educations, ParseJSON.occupations, ParseJSON.incomes, ParseJSON.pics, ParseJSON.locations, ParseJSON.shortlist, ParseJSON.expressinterest);
listView.setAdapter(cl);
}
}
This is the Log where the item data is showing
responde rfi: {"result":[{"id":"Mgl11638","age":"21","height":"160","caste":"Brahmin","community":"Kumaoni","education":"MA","occupation":"Not Working","income":"Will tell later","pic":"Mgl11638.jpg","location":"Almora"},{"id":"Mgl16111","age":"22","height":"160","caste":"Brahmin","community":"Kumaoni","education":"B.Sc","occupation":"Student","income":"Will tell later","pic":"","location":"Almora"},{"id":"Mgl11658","age":"22","height":"154","caste":"Brahmin","community":"Kumaoni","education":"Undergraduate","occupation":"Student","income":"Will tell later","pic":"","location":"Lucknow"},{"id":"Mgl11621","age":"21","height":"134","caste":"Brahmin","community":"Kumaoni","education":"MA","occupation":"Not Working","income":"No income","pic":"","location":"Bareilly"}]}
Why do you use too much of Arrays inside an adapter? Just follow these steps.
Put all your strings inside an Object as single fields.
Pass that object as a parameter into your adapter from your Activity.
Fetch the details from that object in your adapter.
Then the adapter will automatically fetch you multiple data and populate into the list view. And my kind advice is to extend the class as BaseAdapter instead of ArrayAdapter
This is your object. I created it exclusively for you. Create a new java class(not an activity, just a .java file) and put this code inside.
public class DetailsObject implements Serializable {
private static final long serialVersionUID = 1L;
private String id;
private String age;
private String height;
public String community;
public String caste;
public String education;
public String occupation;
public String income;
public byte[] pic;
public String location;
public String shortlist;
public String expressinterest;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
public String getCommunity() {
return community;
}
public void setCommunity(String community) {
this.community = community;
}
public String getCaste() {
return caste;
}
public void setCaste(String caste) {
this.caste = caste;
}
public String getEducation() {
return education;
}
public void setEducation(String education) {
this.education = education;
}
public String getOccupation() {
return occupation;
}
public void setOccupation(String occupation) {
this.occupation = occupation;
}
public String getIncome() {
return income;
}
public void setIncome(String income) {
this.income = income;
}
public byte[] getPic() {
return pic;
}
public void setPic(byte[] pic) {
this.pic = pic;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getShortlist() {
return shortlist;
}
public void setShortlist(String shortlist) {
this.shortlist = shortlist;
}
public String getExpressinterest() {
return expressinterest;
}
public void setExpressinterest(String expressinterest) {
this.expressinterest = expressinterest;
}
}
In your adapter class change extends ArrayAdapter<String> to extends BaseAdapter, change all the String[] to String and in the constructor, juzt pass (Context context, DetailsObject detailObject) as parameter. And in your activity call the adapter like below:
RefineCustomList refineCustomList;
refineCustomList = new RefineCustomList(MainActivity.this,detailObject);
yourListView.setAdapter(refineCustomList);
Thats it..

Getting NullPointerException when call get() methods from model class in Android

I have the following model class:
#SuppressWarnings("serial")
public class Cheltuiala implements Serializable {
private int id;
private Date data;
private String tip;
private float pret;
public Cheltuiala() {
}
public Cheltuiala(Date data, String tip, float pret) {
this.data = data;
this.tip = tip;
this.pret = pret;
}
public int getId() {
return id;
}
public Date getData() {
return data;
}
public String getTip() {
return tip;
}
public float getPret() {
return pret;
}
public void setId(int id) {
this.id = id;
}
public void setData(Date data) {
this.data = data;
}
public void setTip(String tip) {
this.tip = tip;
}
public void setPret(float pret){
this.pret = pret;
}
#Override
public String toString() {
return "id:" + id + " data:" + data + " tip:" + tip + " pret:" + pret;
}
}
Here is the method from the DetailsActivity that extends Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details); // legatura dintre activitate si view
Intent intent = getIntent(); //continutul cu care s-a apelat
final Cheltuiala cheltuiala = (Cheltuiala) intent.getSerializableExtra("cheltuiala");
System.out.println(cheltuiala.getData());
EditText data = (EditText) findViewById(R.id.editTextData);
data.setText(cheltuiala.getData().toString());
EditText tip = (EditText) findViewById(R.id.editTextTip);
System.out.println(cheltuiala);
tip.setText(cheltuiala.getTip());
EditText pret = (EditText) findViewById(R.id.editTextPret);
pret.setText(String.valueOf(cheltuiala.getPret()));
}
When I print 'cheltuiala', I see what I want, but when I call get() methods from 'Cheltuiala' class, I got NullPointerException. Does anyone know why ?
as you have use toString() method you can get NPE when getData is null. you can check getData that is null or not and if is not null use .toString()
you can use following code:
data.setText(cheltuiala.getData() == null ? "" : cheltuiala.getData().toString());
as you say when i use every get method that is null might be data is null. check that you have editTextData id in activity_details

Categories

Resources