EDIT
Got the error, it turns out it is an issue regarding the API version of the emulator. Works fine in higher API version
I am new to Android development and I am trying to build a simple to-do list where items will be added to ListView when a button is clicked. The problem is, the items are not shown in the listview, although they are added and deleted. Please help me identify what I am doing wrong.
Here is my activity_main.xml file
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.erfan.todolist.MainActivity">
<RelativeLayout
android:layout_width="368dp"
android:layout_height="495dp"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="8dp">
<EditText
android:id="#+id/editTextAddItem"
android:hint="Enter Item"
android:layout_width="250dp"
android:layout_height="50dp"
android:layout_weight="4"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
<Button
android:id="#+id/buttonAddItem"
android:text="Add"
android:layout_width="100dp"
android:layout_height="50dp"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true" />
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_below="#+id/editTextAddItem"
android:layout_marginTop="23dp" />
</RelativeLayout>
</android.support.constraint.ConstraintLayout>
Here is my MainActivity.java file
package com.example.erfan.todolist;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
EditText vEditTextAddItem;
Button vButtonAddItem;
ListView vListViewItemList;
ArrayList<String> items;
ArrayAdapter<String> adapter;
public static final String FILENAME = "data.dat";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
vEditTextAddItem = (EditText) findViewById(R.id.editTextAddItem);
vButtonAddItem = (Button) findViewById(R.id.buttonAddItem);
vListViewItemList = (ListView) findViewById(R.id.listView);
items = readData(getApplicationContext());
adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.support_simple_spinner_dropdown_item, items);
vListViewItemList.setAdapter(adapter);
vButtonAddItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonAddItem:
String itemEntered = vEditTextAddItem.getText().toString();
adapter.add(itemEntered);
vEditTextAddItem.setText("");
writeData(items, getApplicationContext());
Toast.makeText(getApplicationContext(), "Item is added", Toast.LENGTH_SHORT).show();
break;
}
}
});
vListViewItemList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
items.remove(position);
adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Item Deleted", Toast.LENGTH_SHORT).show();
}
});
}
public static void writeData(ArrayList<String> items, Context context) {
try {
FileOutputStream fileOutputStraStream = context.openFileOutput(FILENAME, Context.MODE_PRIVATE);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStraStream);
objectOutputStream.writeObject(items);
objectOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static ArrayList<String> readData(Context context) {
ArrayList<String> itemList = null;
try {
FileInputStream fileInputStream = context.openFileInput(FILENAME);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
itemList = (ArrayList<String>) objectInputStream.readObject();
} catch (FileNotFoundException e) {
itemList = new ArrayList<>();
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
itemList = new ArrayList<>();
e.printStackTrace();
}
return itemList;
}
}
I am attaching the screenshot of the emulator as well
When the item is added, no item is showing in the ListView.
Got the error, it turns out it is an issue regarding the API version of the emulator. Works fine in higher API version
Related
I want to create an activity to search for users by full name. I created everything I needed and it worked properly, except for one thing. When I press search button the result are not show in recyclerview. I need to go back and the the results are shown. I need to do these 2 steps to see the results.
Yes the search bar and view holder are overlap, I will try to fixed later. Do you know how to make it so that once searched the results are displayed immediately without having to go back
This is my layout for view holder
<?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="75dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp"
android:id="#+id/parent_layout"
android:background="#drawable/recycler_view_border">
<com.mikhaellopez.circularimageview.CircularImageView
android:id="#+id/imageProfile"
android:layout_width="60dp"
android:layout_height="60dp"
android:tint="#808080"
android:layout_marginStart="10dp"
android:layout_marginTop="7dp"
app:civ_border_color="#color/dark_blue"
app:civ_border_width="2dp"
app:srcCompat="#drawable/defaultimage"/>
<TextView
android:id="#+id/userFullName"
android:layout_toEndOf="#+id/imageProfile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:layout_marginEnd="20dp"
android:layout_marginStart="10dp"
android:gravity="center"
android:text="#string/fullname"
android:textSize="16sp"
android:textColor="#color/black"/>
<com.google.android.material.button.MaterialButton
android:id="#+id/buttonAdd"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginTop="13dp"
android:layout_marginEnd="10dp"
android:layout_marginStart="340dp"
android:background="#drawable/btn_background"
app:cornerRadius="8dp"
android:drawableTop="#drawable/ic_action_add" />
</RelativeLayout>
This is my layout for activity
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SendFriendRequests">
<LinearLayout
android:id="#+id/linearlayout"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_marginLeft="13dp"
android:orientation="vertical"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<EditText
android:id="#+id/searchUsername"
android:layout_width="318dp"
android:layout_height="45dp"
android:layout_marginTop="20dp"
android:background="#drawable/edt_background"
android:hint="#string/searchFriends"
android:imeOptions="actionNext"
android:importantForAutofill="no"
android:inputType="text"
android:paddingStart="16dp"
android:paddingEnd="16dp" />
<com.google.android.material.button.MaterialButton
android:id="#+id/buttonSearch"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginStart="333dp"
android:layout_marginTop="-47dp"
android:layout_marginEnd="10dp"
android:background="#drawable/btn_background"
android:drawableTop="#drawable/ic_action_search"
app:cornerRadius="8dp" />
</LinearLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="580dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="#+id/linearlayout"
app:layout_constraintVertical_bias="0.99"
tools:layout_editor_absoluteX="-16dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
This is my adapter
package com.example.chatappjava;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.mikhaellopez.circularimageview.CircularImageView;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
public class SendFriendRequestAdapter extends RecyclerView.Adapter<SendFriendRequestAdapter.ViewHolder> {
private static final String TAG = "ContactsAdapter";
private ArrayList<UserData> arrayListUserData = new ArrayList<>();
private Context context;
public SendFriendRequestAdapter(ArrayList<UserData> arrayListUserData, Context context) {
this.arrayListUserData = arrayListUserData;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_send_friend_request_item, parent, false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(ViewHolder holder, #SuppressLint("RecyclerView") int position) {
Log.d(TAG, "onBindViewHolder: called.");
Glide.with(context)
.asBitmap()
.load(arrayListUserData.get(position).image)
.into(holder.userProfileImage);
holder.userFullName.setText(arrayListUserData.get(position).name);
holder.buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
Connection conn = DatabaseConnection.createDatabaseConnection();
PreparedStatement st1 = conn.prepareStatement(
" insert into FRIEND_REQUESTS values (?,?,?)");
st1.setString(1, arrayListUserData.get(position).friendId);
st1.setString(2, arrayListUserData.get(position).userId);
st1.setInt(3, 0);
st1.execute();
showToast("Friend request is sended");
Intent intent = new Intent(context, MainActivity.class);
intent.putExtra("IdAccount", arrayListUserData.get(position).userId);
context.startActivity(intent);
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
});
holder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context.getApplicationContext(), specificchat.class);
intent.putExtra("userId", arrayListUserData.get(position).userId);
intent.putExtra("friendId", arrayListUserData.get(position).friendId);
intent.putExtra("friendName", arrayListUserData.get(position).name);
intent.putExtra("friendImage", arrayListUserData.get(position).image);
context.startActivity(intent);
}
});
}
private void showToast(String message) {
Toast.makeText(context.getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
#Override
public int getItemCount() {
return arrayListUserData.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
CircularImageView userProfileImage;
TextView userFullName;
RelativeLayout parentLayout;
Button buttonAdd;
public ViewHolder(View itemView) {
super(itemView);
userProfileImage = itemView.findViewById(R.id.imageProfile);
userFullName = itemView.findViewById(R.id.userFullName);
parentLayout = itemView.findViewById(R.id.parent_layout);
buttonAdd = itemView.findViewById(R.id.buttonAdd);
}
}
}
And this is my java class which use the adapter
package com.example.chatappjava;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
public class SendFriendRequests extends AppCompatActivity {
private ArrayList<UserData> arrayListUserData = new ArrayList<>();
private Button searchButton;
private EditText searchUsername;
private String userId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
userId = intent.getStringExtra("IdAccount");
setContentView(R.layout.activity_send_friend_request);
searchButton = findViewById(R.id.buttonSearch);
searchUsername = findViewById(R.id.searchUsername);
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
Connection conn = DatabaseConnection.createDatabaseConnection();
Statement statement = conn.createStatement();
ResultSet resultat = statement.executeQuery("select ID, FULLNAME, IMAGE from USERS where ID not in (select FRIEND_ID from FRIENDSLIST where USER_ID = " + userId + ") and FULLNAME like '%" + searchUsername.getText().toString() + "%' and ID not in (select RECEIVER_ID from FRIEND_REQUESTS where SENDER_ID = " + userId + ")");
while (resultat.next()) {
arrayListUserData.add(new UserData(resultat.getString("FULLNAME"), resultat.getString("IMAGE"), resultat.getString("ID"), userId));
}
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
initRecycleView();
}
});
}
private void initRecycleView() {
RecyclerView recyclerView = findViewById(R.id.recyclerView);
SendFriendRequestAdapter adapter = new SendFriendRequestAdapter(arrayListUserData, this);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
}
I think it's the RecyclerView in your XML that needs to be adjusted at android:layout_height = "0dp"
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="#+id/linearlayout"/>
When I write query in Searchview a list of items(Suggestions list) is apppeared and filtered as per the QueryText changed. When i click the list item the text of filtered list does not appear in the search view.
I want the filtered list item to appear in the search view when clicked. But Here the Item of the unfiltered list appears when i click the filtered list
How can I Solve this problem?
Xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MySearchView"
android:orientation="vertical"
android:padding="30dp">
<SearchView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:queryHint="Search here..."
android:iconifiedByDefault="false"
android:focusedByDefault="true"
android:transitionName="Search_box"
android:id="#+id/search_view">
</SearchView>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:id="#+id/list_view">
</ListView>
</LinearLayout>
java file:
package edmt.dev.androidgridlayout;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;
import com.androidnetworking.AndroidNetworking;
import com.androidnetworking.common.Priority;
import com.androidnetworking.error.ANError;
import com.androidnetworking.interfaces.JSONArrayRequestListener;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import edmt.dev.androidgridlayout.HelperClasses.HomeAdapter.FeaturedHelperClass;
import edmt.dev.androidgridlayout.HelperClasses.HomeAdapter.ProductAdapter;
public class MySearchView extends AppCompatActivity {
SearchView searchView;
ListView listView;
ArrayList<String> list,catid;
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_search_view);
searchView=findViewById(R.id.search_view);
searchView.requestFocusFromTouch();
listView=findViewById(R.id.list_view);
list =new ArrayList<String>();
catid =new ArrayList<String>();
String url = getResources().getString(R.string.url);
String SelectCategory = url + "request=SelectCategory";
System.out.println(SelectCategory);
AndroidNetworking.get(SelectCategory)
.setPriority(Priority.LOW)
.build()
.getAsJSONArray(new JSONArrayRequestListener() {
#Override
public void onResponse(JSONArray response) {
JSONObject jo;
try {
for (int i = 0; i < response.length(); i++) {
jo = response.getJSONObject(i);
String sid = jo.getString("id");
String sname = jo.getString("title");
list.add(sname);
catid.add(sid);
}
adapter=new ArrayAdapter<>(getApplicationContext(),R.layout.dropdown_item,list);
listView.setAdapter(adapter);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "JSON Error" + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
#Override
public void onError(ANError anError) {
anError.printStackTrace();
Toast.makeText(getApplicationContext(), "unsuccessful : error is :" + anError.getMessage(), Toast.LENGTH_LONG).show();
}
});
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
Intent intent=new Intent(getApplicationContext(),AllProductPage.class);
intent.putExtra("categoryid","0");
intent.putExtra("categorytitle",query);
intent.putExtra("request","MySearchView");
startActivity(intent);
Toast.makeText(getApplicationContext(),"searchview"+query,Toast.LENGTH_SHORT).show();
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return false;
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
searchView.setQuery(list.get(position),false);
}
});
}
}
I have created a clickable ListView with a TextView on the new page. I would like to display JSON data in this TextView, and I want the JSON data to be retrieved by clicking the ListView item i.e. opening the new page. Is this possible?
Below you will find the code I have so far. The ListView is clickable and functions correctly, but the JSON code does not.
If you know the solution to my problem, you're a superstar! Thank you in advance.
MainActivity.java
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
public class MainActivity extends AppCompatActivity {
String[] names = {
"A",
"B"
};
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayAdapter adapter = new ArrayAdapter(this, R.layout.list_view, names);
listView = (ListView) findViewById(R.id.listview);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this, "Searching " + names[position], Toast.LENGTH_LONG).show();
Intent intent = new Intent(MainActivity.this, DetailActivity.class);
intent.putExtra("names", names[position]);
startActivity(intent);
}
public void onClick(View view) {
try {
JSONArray reader = new JSONArray(readJSONFromAsset());
ListView tvData = (ListView) findViewById(R.id.listview);
TextView tvContext = (TextView) findViewById(R.id.detail);
String codeArray = tvData.getAdapter().toString();
for (int x = 0; x < reader.length(); x++) {
JSONObject Array = reader.getJSONObject(x);
String data = Array.getString("data");
String context = Array.getString("context");
if (data.equals(codeArray)) {
tvContext.setText(context);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public String readJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("data.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
});
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ListView
android:id="#+id/listview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</android.support.constraint.ConstraintLayout>
DetailActivity.java
package com.example.steen.array;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class DetailActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
TextView textView = (TextView)findViewById(R.id.detail);
textView.setText(getIntent().getStringExtra("names"));
}
}
activity_detail.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".DetailActivity">
<TextView
android:id="#+id/detail"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</android.support.constraint.ConstraintLayout>
list_view.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
</TextView>
data.json
[
{
"data": "A",
"context": "(A) if you see this, JSON is working"
},
{
"data": "B",
"context": "(B) if you see this, JSON is working"
}
]
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 get how to do this for a simple ListView, something like:
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
But whenever I do it in my activity I get a nullpointerexception.
Could someone please show me how it is supposed to be? Thanks!
EDIT: I'm sorry! Didn't want to fill up an entire question only with code, I think it's necessary in this case, so I'm putting my entire java code below:
import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
public class Save extends ListActivity {
String FileName;
EditText et;
String listItem[]={};
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_save);
Button save = (Button) findViewById(R.id.SAVE); //this is my button
final EditText title = (EditText) findViewById(R.id.save_filename); //This is unused
final EditText maintext = (EditText) findViewById(R.id.test);
getActionBar().setDisplayUseLogoEnabled(false);
getActionBar().setDisplayHomeAsUpEnabled(true);
et = (EditText) findViewById(R.id.save_filename);
listView = (ListView) findViewById(R.id.list); //I've specified this listView only for the OnItemClickListener action
List values = new ArrayList();
for (int i = 0; i < listItem.length; i++) {
values.add(listItem[i]);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
FileName = et.getText().toString() + ".txt";
FileOutputStream fout = openFileOutput(FileName, Context.MODE_PRIVATE);
OutputStreamWriter outsw = new OutputStreamWriter(fout);
try {
outsw.write(String.valueOf(maintext));
outsw.flush();
outsw.close();
Toast.makeText(getBaseContext(), "Your file has been saved", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
ArrayAdapter<String> adapter = (ArrayAdapter<String>) getListAdapter();
String device;
switch (view.getId()) {
case R.id.SAVE:
List myList = new ArrayList();
device = et.getText().toString();
myList.add(device);
adapter.add(device);
et.setText("");
break;
}
adapter.notifyDataSetChanged();
}
});
//I think this is wrong, I get no error in Java by the way. How could this work if there's a specific extension for my activity that define the listview? **That's my question**.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// ListView Clicked item index
int itemPosition = position;
// ListView Clicked item value
String itemValue = (String) listView.getItemAtPosition(position);
// Show Alert
Toast.makeText(getApplicationContext(),
"Position :"+itemPosition+" ListItem : " +itemValue , Toast.LENGTH_LONG)
.show();
}
});
}
And the xml:
<Button
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="#+id/SAVE"
android:text="#string/save_button" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/save_filename"
android:layout_alignRight="#+id/linearLayout"
android:hint="#string/save_hint"
android:layout_alignEnd="#+id/linearLayout"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginBottom="5dp" />
<ListView
android:id="#android:id/list"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_above="#+id/linearLayout"
android:layout_below="#+id/save_filename">
</ListView>
Sorry again for the cunfusion!!
The problem here comes from the fact that you are using ListActivity instead of Activity. For this reason the ListView's ID is not added to the R file so it is not callable by the findById call. This would not happen if Activity were used. When using ListActivity you can use the built in getListView() method to get the ListView object.
Also when I ran your given code I got an error that a listView had to be defined by the ID list. This comes from an error in your XML file when you defined the ID.
Below I posted two sections from your given XML
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/save_filename"
<ListView
android:id="#android:id/list"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_above="#+id/linearLayout"
android:layout_below="#+id/save_filename">
</ListView>
Notice when defining the id, the top one says android:id="#+id/save_filename" while the bottom says android:id="#android:id/list". Also when you use save_file_name it is done like thisandroid:layout_below="#+id/save_filename"This is incorrect. To define an id you use#+id`. This should be done the first time an element is referenced. It tells android to generate a value for it in R.java. Errors like this in your XML can cause your R.java file to not be generated and lead to different problems but I think the extra pluses on the ids are forgivable.
I was getting the error because of how you defined the id for layout. Instead it should look more like this
android:id="#+id/android:list"
Notice the + to create a new id and because I am using ListActivity I also must define it as android:list instead of just list.
I changed your XML to this:
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/save_filename"
android:layout_alignRight="#+id/linearLayout"
android:hint="save here"
android:layout_alignEnd="#id/linearLayout"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginBottom="5dp" />
<ListView
android:id="#+id/android:list"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_above="#id/linearLayout"
android:layout_below="#id/save_filename">
</ListView>
Here is some corrected code, I noted what I changed.
package com.example.sosandbox;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class Save extends ListActivity {
String FileName;
EditText et;
//Added some test values
String listItem[]={"1","2","3","4","5"};
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_save);
Button save = (Button) findViewById(R.id.SAVE); //this is my button
// This is unused so I commented it out
// final EditText title = (EditText) findViewById(R.id.save_filename); //This is unused
final EditText maintext = (EditText) findViewById(R.id.save_filename);
getActionBar().setDisplayUseLogoEnabled(false);
getActionBar().setDisplayHomeAsUpEnabled(true);
et = (EditText) findViewById(R.id.save_filename);
// This is your issue.
// listView = (ListView) findViewById(R.id.list);
// Change it to this because you are using a listActivity
listView = getListView();//I've specified this listView only for the OnItemClickListener action
List values = new ArrayList();
// This won't run because you initilize listItem to an empty array or 0 so 0 < 0 evaluates to false and the loop doesn't run
for (int i = 0; i < listItem.length; i++) {
values.add(listItem[i]);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
FileName = et.getText().toString() + ".txt";
FileOutputStream fout = openFileOutput(FileName, Context.MODE_PRIVATE);
OutputStreamWriter outsw = new OutputStreamWriter(fout);
try {
outsw.write(String.valueOf(maintext));
outsw.flush();
outsw.close();
Toast.makeText(getBaseContext(), "Your file has been saved", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
ArrayAdapter<String> adapter = (ArrayAdapter<String>) getListAdapter();
String device;
switch (view.getId()) {
case R.id.SAVE:
List myList = new ArrayList();
device = et.getText().toString();
myList.add(device);
adapter.add(device);
et.setText("");
break;
}
adapter.notifyDataSetChanged();
}
});
//I think this is wrong, I get no error in Java by the way. How could this work if there's a specific extension for my activity that define the listview? **That's my question**.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// ListView Clicked item index
int itemPosition = position;
// ListView Clicked item value
String itemValue = (String) listView.getItemAtPosition(position);
// Show Alert
Toast.makeText(getApplicationContext(),
"Position :"+itemPosition+" ListItem : " +itemValue , Toast.LENGTH_LONG)
.show();
}
});
}
}