the specified child already has a parent .you must call removeView() - android-layout

For some reason, I keep receiving the following error:
java.lang.IllegalStateException: the specified child already has a parent. You must call removeView() on the child's parent view
I am using the following code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listitem);
//url is fetched from another class
readWebpage(imdbUrl);
}
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
}
#Override
protected void onPostExecute(String result) {
//textView.setText(result);
displayMoviesList(result);
}
}
public void readWebpage(String imdbUrl) {
}
public void displayMoviesList(String result) {
JSONObject responseObj = null;
try {
responseObj = new JSONObject(result);
JSONObject Obj = responseObj.getJSONObject("results");
JSONArray moviesListObj = Obj.getJSONArray("result");
for(int i=0 ;i<moviesListObj.length();i++) {
JSONObject e = moviesListObj.getJSONObject(i);
cover[i] = e.getString("cover");
title[i] = e.getString("title");
year[i] = e.getString("year");
director[i] = e.getString("director");
rating[i] = e.getString("rating");
details[i] = e.getString("details");
}
tl = (TableLayout) findViewById(R.id.main_table);
imgView = (ImageView)findViewById(R.id.imageID);
progressbar = (ProgressBar) findViewById(R.id.loadingBar);
//new loadImageTask().execute(cover[i].toString());
new loadImageTask().execute( URL);// it calls another function..
TextView title = (TextView)findViewById(R.id.titleID);
title.setText("TEXT");
TableRow tr = new TableRow(this);
tr.addView(imgView);
tr.addView(title);
tl.addView(tr, new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
} catch(JSONException e) {
//Log.e("log_tag", "Error parsing data " + e.toString());
}
I am not sure why I'm receiving the error, but it appears to be being generated while I am adding it to the view.

Solution is that we either we define the rows in .xml file or in our .java file. I was adding the rows dynamically in my java file and using addView. So in .xml file we cannot add another view (we should not add rows for the same).

Related

Cannot run a background task in andorid studio using AsyncTask

I am trying to run a task at background using AsyncTask, but it isn't working
I have tried a lot of solutions but none worked. My code should show me html codes of prothomalo.com at the logcat, but is is not doing that, instead it is showing a lot of errors.
public class BG extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.d("myBG", "onPreExecute: ran");
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.d("myBG", "onPostExecute: ran");
Log.d("myBG", s);
}
#Override
protected String doInBackground(String... urls) {
Log.d("myBG", "doInBackground: ran");
String result = "";
URL url;
HttpURLConnection conn;
try {
url = new URL(urls[0]);
conn = (HttpURLConnection) url.openConnection();
InputStream in = conn.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
} catch (Exception e) {
e.printStackTrace();
return "Something went wrong";
}
return result;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
text = findViewById(R.id.text8);
BG myTask = new BG();
myTask.execute("https://www.prothomalo.com");
}
}The logcat should show if my background activity has run or not, but it showing a lot of errors

I want add multiple Data Items of same date in single Card View in Android

I want data to be displayed as shown in imageenter image description here
I want to add multiple item of same date in single card view instead of creating another card view for the item of same date
I have tried in Android Studio grouping recycler view called as sanctioned Recycler view where I used date as header but it's not the solution
My Adapter Class
private Context mContext;
List<ListItem> consolidatedList = new ArrayList<>();
public AttendanceAdapter(Context context, List<ListItem>
consolidatedList) {
this.consolidatedList = consolidatedList;
this.mContext = context;
}
#Override
public RecyclerView.ViewHolder
onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder viewHolder = null;
LayoutInflater inflater =
LayoutInflater.from(parent.getContext());
switch (viewType) {
case ListItem.TYPE_GENERAL:
View v1 =
inflater.inflate(R.layout.attendance_adapter_layout, parent,
false);
viewHolder = new GeneralViewHolder(v1);
break;
case ListItem.TYPE_DATE:
View v2 =
inflater.inflate(R.layout.attn_item_header, parent, false);
viewHolder = new DateViewHolder(v2);
break;
}
return viewHolder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder
viewHolder, int position)
{
switch (viewHolder.getItemViewType()) {
case ListItem.TYPE_GENERAL:
GeneralItem generalItem = (GeneralItem)
consolidatedList.get(position);
GeneralViewHolder generalViewHolder=
(GeneralViewHolder) viewHolder;
//generalViewHolder.txt_date.setText(
generalItem.getAttendance_data().getDate());
generalViewHolder.txt_month.setText(
generalItem.getAttendance_data().getMonth_name());
generalViewHolder.txt_date.setText(
generalItem.getAttendance_data().getDate_no());
generalViewHolder.txt_out.setText(
generalItem.getAttendance_data().getAttn_out_time());
generalViewHolder.txt_in.setText(
generalItem.getAttendance_data().getAttn_In_time());
generalViewHolder.txtreason.setText
(generalItem.getAttendance_data().getRemark());
break;
case ListItem.TYPE_DATE:
DateItem dateItem = (DateItem)
consolidatedList.get(position);
DateViewHolder dateViewHolder = (DateViewHolder) viewHolder;
dateViewHolder.txtTitle.setText(dateItem.getDate());
// Populate date item data here
break;
}
}
class DateViewHolder extends RecyclerView.ViewHolder {
protected TextView txtTitle;
public DateViewHolder(View v) {
super(v);
this.txtTitle = (TextView)
v.findViewById(R.id.attn_date);
}
}
// View holder for general row item
class GeneralViewHolder extends RecyclerView.ViewHolder {
protected TextView
txt_in,txtreason,txt_out,txt_date,txt_month;
public GeneralViewHolder(View v) {
super(v);
this.txt_in =v.findViewById(R.id.attn_in_txt);
this.txt_out=v.findViewById(R.id.attn_out_txt);
this.txtreason=v.findViewById(R.id.attn_reason_txt);
this.txt_date=v.findViewById(R.id.date_view);
this.txt_month=v.findViewById(R.id.month_view);
}
}
#Override
public int getItemViewType(int position) {
return consolidatedList.get(position).getType();
}
#Override
public int getItemCount() {
return consolidatedList != null ? consolidatedList.size() : 0;
}
}
MainActivity.Java
public class CurrentMonth extends AsyncTask<Void,Void,Void> {
#Override
protected Void doInBackground(Void... voids) {
attn_list_data_cur_month();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
updateUi();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
public void attn_list_data_cur_month(){
try {
this.connection=createConnection();
Statement stmt=connection.createStatement();
Calendar current_month_data = Calendar.getInstance();
current_month_data.add(Calendar.MONTH, 0);
//Calendar current_month_date = Calendar.getInstance();
//current_month_date.set(Calendar.DAY_OF_MONTH,0);
n=current_month_data.get(Calendar.DAY_OF_MONTH);
String current_month_year = new SimpleDateFormat("MMM-
yyyy").format(current_month_data.getTime());
String month_name=currentMonth.getText().toString();
for (int i=1;i<=n;i++) {
String date = i + "-" + current_month_year;
ResultSet resultSet = stmt.executeQuery("Select * from
MATTN_MAS where ATTN_DATE='" + date + "' and Username='" +
Username + "'");
String Attn_Type;
if (resultSet.next()) {
while (resultSet.next()) {
Attn_Type = resultSet.getString(8);
String Time = null;
String Reason = resultSet.getString(11);
if (Attn_Type.equals("I")) {
String Attn_Type_In = "I";
String Attn_Type_Out = null;
StringBuilder stringBuilder = new StringBuilder("" + i);
String date_no = stringBuilder.toString();
myOptions.add(new Attendance_Data(Attn_Type_In,
date, Reason, Attn_Type_Out, i, date_no, month_name));
} else {
String Attn_Type_Out = "O";
String Attn_Type_In = null;
StringBuilder stringBuilder = new StringBuilder("" + i);
String date_no = stringBuilder.toString();
myOptions.add(new Attendance_Data(Attn_Type_In,
date, Reason, Attn_Type_Out, i, date_no, month_name));
}
}
} else {
Attn_Type = "Absent";
String Time = null;
String Reason = null;
String out = null;
StringBuilder stringBuilder = new StringBuilder("" + i);
String date_no = stringBuilder.toString();
myOptions.add(new Attendance_Data(Attn_Type, date, Reason,
out, i, date_no, month_name));
}
}
}catch (Exception e){
System.out.println("my Error"+e);
}
}
public void updateUi(){
//sortedData= (List<PojoOfJsonArray>)
PojoOfJsonArray.sortList(myOptions);
HashMap<String, List<Attendance_Data>> groupedHashMap =
groupDataIntoHashMap(myOptions);
for (String date1 : groupedHashMap.keySet()) {
DateItem dateItem = new DateItem();
dateItem.setDate(date1);
consolidatedList.add(dateItem);
for (Attendance_Data pojoOfJsonArray : groupedHashMap.get(date1))
{
GeneralItem generalItem = new GeneralItem();
generalItem.setAttendance_data(pojoOfJsonArray);
consolidatedList.add(generalItem);
}
}
adapter = new AttendanceAdapter(this, consolidatedList);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
attn_report_view.setLayoutManager(layoutManager);
attn_report_view.setAdapter(adapter);
}
private HashMap<String, List<Attendance_Data>>
groupDataIntoHashMap(List<Attendance_Data> listOfPojosOfJsonArray) {
HashMap<String, List<Attendance_Data>> groupedHashMap = new HashMap<>
();
for (Attendance_Data pojoOfJsonArray : listOfPojosOfJsonArray) {
String hashMapKey = pojoOfJsonArray.getDate();
if (groupedHashMap.containsKey(hashMapKey)) {
// The key is already in the HashMap; add the pojo object
// against the existing key.
groupedHashMap.get(hashMapKey).add(pojoOfJsonArray);
} else {
List<Attendance_Data> list = new ArrayList<>();
list.add(pojoOfJsonArray);
groupedHashMap.put(hashMapKey, list);
}
}
return groupedHashMap;
}
I want to add multiple items of same date in same single single card view but instead it is creating multiple Card View for multiple items of same date
You have to use RecyclerView Multiple ViewTypes. for detail please check this example.
Also visit this example.
Yeah I found the solution it worked perfect for Me.....we
have to just make changes to the card View by removing
spaces..
.
like this below...
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardMaxElevation="0.1dp"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:background="#303030"
card_view:cardElevation="5dp"
android:foreground="?android:attr/selectableItemBackground"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_marginLeft="#dimen/dp_2"
android:layout_marginRight="#dimen/dp_2">
<...Your All Text Boxes and further Layout inside this
cardView...>
</android.support.v7.widget.CardView>
and I have add Header for each CardView....and it looks like
this
Outout is shown in below image

Creating a very custom list

I'm developping an application, and now, I don't know what to do next:
I have a list of elements, each element has some informations + an ID + a logo.
What I want to do is creating a list like in the picture
List
Of course, I want it in a single layer, with the logo, some informations, and a button to define an action; where I could use the ID of the selected item.
I did some research, may be I found some relative subjects, but none of what I want.
My list is a
ArrayList<ArrayList<String>>
filled by data from database.
Thank you
Here it is:
public class Avancee extends Activity {
// Log tag
private static final String TAG = MainActivity2.class.getSimpleName();
// Movies json url
private static final String url = "http://blabla.com/movie.json";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list);
adapter = new CustomListAdapter(this, movieList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// changing action bar color
getActionBar().setBackgroundDrawable(
new ColorDrawable(Color.parseColor("#1b1b1b")));
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Log.d(TAG, response.toString());
hidePDialog();
String result = getIntent().getStringExtra("ITEM_EXTRAA");
System.out.println(result);
try{
JSONArray ja = new JSONArray(result);
for (int i = 0; i < ja.length(); i++) {
try {
JSONObject obj = ja.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(obj.getString("title"));
movie.setLocation(obj.getString("location_search_text"));
movie.setId(obj.getInt("id"));
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
It's the "id" that I want to get in the OnClick event.
use this code
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Movie movie= movieList.get(position);
}
});
//here position will give you the id of listview cell so you can use it like
Movie movie= movieList.get(position);
then you can use it get all the data inside your moview object

Parse.com can't retrieve objects

I'm trying to retrieve objects using parse, however I get the error
gameScore cannot be resolved.
I'm following the exact explanation on https://parse.com/docs/android_guide#objects-classes
What am I doing wrong ?
public class ParseStarterProjectActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ParseAnalytics.trackAppOpenedInBackground(getIntent());
ParseQuery<ParseObject> query = ParseQuery.getQuery("GameScore");
query.getInBackground("gDlXAym3S7", new GetCallback<ParseObject>() {
public void done(ParseObject object, ParseException e) {
if (e == null) {
System.out.println("object found");
int score = gameScore.getInt("score");
String playerName = gameScore.getString("playerName");
boolean cheatMode = gameScore.getBoolean("cheatMode");
} else {
System.out.println("object not found");
}
}
});
}
}
I'm looking to your code and you don't declare any class called "gameScore". I think what you want is the next code:
public class ParseStarterProjectActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ParseAnalytics.trackAppOpenedInBackground(getIntent());
ParseQuery<ParseObject> query = ParseQuery.getQuery("GameScore");
query.getInBackground("gDlXAym3S7", new GetCallback<ParseObject>() {
public void done(ParseObject object, ParseException e) {
if (e == null) {
System.out.println("object found");
int score = object.getInt("score");
String playerName = object.getString("playerName");
boolean cheatMode = object.getBoolean("cheatMode");
} else {
System.out.println("object not found");
}
}
});
}
}
So pay attention to the ParseObject you get after the query is done: it's declared as "object", and you will need it to get all information stored inside of it.
Hope it helps, Regards!!
In addition to Fer answer You should check if object id in: query.getInBackground("gDlXAym3S"... is right, and check if this object have Public Read access in Parse dashboard (column: ACL).

Getting error while calling library jar file in j2me

I have created a login page with webservice in j2me. But while running I am getting error. Can anyone please help? My code is:
public class Login extends MIDlet implements CommandListener {
//the main form
Form mainForm = null;
//the text-boxes for the input
TextField txtBoxA = null;
TextField txtBoxB = null;
//the result label
//the Exit command
Command cmdExit = null;
Command cmdAdd = null;
//the Display reference
Display display = null;
public Login() {
{
//construct the main form
mainForm = new Form("kSOAP Example");
//construct the controls
txtBoxA = new TextField("UserName:", null, 50, TextField.ANY);
txtBoxB = new TextField("Password:", null, 50, TextField.ANY);
// result = new StringItem("Result:", null);
//add controls to the form
mainForm.append(txtBoxA);
mainForm.append(txtBoxB);
// mainForm.append(result);
//construct commands
cmdExit = new Command("Exit", Command.EXIT, 1);
cmdAdd = new Command("Add", Command.SCREEN, 1);
//add commands
mainForm.addCommand(cmdAdd);
mainForm.addCommand(cmdExit);
}
}
public void startApp() {
if (display == null) {
display = Display.getDisplay(this);
}
//display the main form
display.setCurrent(mainForm);
//register the command listener
mainForm.setCommandListener(this);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void commandAction(Command c, Displayable d) {
if (c == cmdExit) {
this.destroyApp(false);
this.notifyDestroyed();
} else if (c == cmdAdd) {
//callWebServiceMethod();
Library lib=new Library();
lib.init();
}
}
my jar file coding is library.jar
public class Library {
String METHOD_NAME = "ValidateLogin_M";
String SOAP_ACTION ="http://64.244.69.235:81/MobileApp/ValidateLogin_M";
String NAMESPACE ="http://64.244.69.235:81/MobileApp/";
String URL ="http://64.244.69.235:81/MobileApp/service1.asmx";
public Library() {
// TODO Auto-generated constructor stub
}
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Library lib=new Library();
lib.init();
}
public void init()
{
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
String user= "gsrtestnew#gmail.com";
String password= "123456";
request.addProperty("UserID",user);
request.addProperty("Password",password);
SoapSerializationEnvelope envelope =
new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransport j2meHttpTransport = new HttpTransport(URL);
try {
j2meHttpTransport.call(SOAP_ACTION, envelope);
SoapObject content = (SoapObject) envelope.bodyIn;
String sum = content.getProperty(0).toString();
// result.setText(sum);
System.out.println("##########"+sum);
JSONArray jsonobj = new JSONArray(sum.toString());
System.out.println("Json obj length:: " + jsonobj.length());
if(jsonobj.length() == 0)
{
}
for(int i=0; i<jsonobj.length(); i++)
{
JSONObject jobj = jsonobj.getJSONObject(i);
String CustID = jobj.getString("CustID");
System.out.println("CustID is :: "+CustID);
String Email = jobj.getString("Email");
System.out.println("Email is :: "+Email);
String FirstName = jobj.getString("FirstName");
System.out.println("FirstName is :: "+FirstName);
String LastName = jobj.getString("LastName");
System.out.println("LastName is :: "+LastName);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
I have imported the jar file and called as Library class. But still I am getting error.
My error is
Starting emulator in execution mode
Installing suite from: http://127.0.0.1:49412/WebApplication.jad
TRACE: <at java.lang.Error: ClassFormatError: 56>, Exception caught in Display class
java.lang.Error: ClassFormatError: 56
at com.web.application.Login.commandAction(Login.java:95)
at javax.microedition.lcdui.Display$ChameleonTunnel.callScreenListener(), bci=46
at com.sun.midp.chameleon.layers.SoftButtonLayer.processCommand(), bci=74
at com.sun.midp.chameleon.layers.SoftButtonLayer.commandSelected(), bci=11
at com.sun.midp.chameleon.layers.MenuLayer.pointerInput(), bci=170
at com.sun.midp.chameleon.CWindow.pointerInput(), bci=76
at javax.microedition.lcdui.Display$DisplayEventConsumerImpl.handlePointerEvent(), bci=19
at com.sun.midp.lcdui.DisplayEventListener.process(), bci=296
at com.sun.midp.events.EventQueue.run(), bci=179
at java.lang.Thread.run(Thread.java:722)
This has already been answered - jvm cannot load a class due to difference in version - cf - ClassFormatError: 56 while using hessian in j2me
Recompile with
javac -target 1.4 ...

Resources