Unable to start activity ComponentInfo{com.example.myapplication/com.example.myapplication.MainActivity} - java

Main activity.xml
<?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"
android:background="#color/colorPrimary"
android:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:orientation="horizontal">
<EditText
android:id="#+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="4"
android:background="#android:color/white"
android:ems="10"
android:hint="Add a Note"
android:textColor="#android:color/black"
android:inputType="textPersonName" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button" />
</LinearLayout>
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
MainActivity.java
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
EditText item;
Button add;
ListView listView;
ArrayList<String> itemList = new ArrayList<>();
ArrayAdapter<String> arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
item = findViewById(R.id.editText);
add = findViewById(R.id.button);
listView = findViewById(R.id.list);
itemList = FileHelper.readData(this);
arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,android.R.id.text1,itemList);
listView.setAdapter(arrayAdapter);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String itemName = item.getText().toString();
itemList.add(itemName);
item.setText("");
FileHelper.writeData(itemList,getApplicationContext());
arrayAdapter.notifyDataSetChanged();
}
});
}
}
FileHelper.java
package com.example.myapplication;
import android.content.Context;
import android.os.Build;
import androidx.annotation.RequiresApi;
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;
public class FileHelper {
public static final String FILENAME = "listinfo.dat";
public static void writeData(ArrayList<String> item, Context context)
{
try {
FileOutputStream fos = context.openFileOutput(FILENAME, Context.MODE_PRIVATE);
ObjectOutputStream oas = new ObjectOutputStream(fos);
oas.writeObject(item);
oas.close();
} catch (FileNotFoundException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
}
public static ArrayList<String> readData(Context context){
ArrayList<String> itemList = null;
try {
FileInputStream fis = context.openFileInput(FILENAME);
ObjectInputStream ois = new ObjectInputStream(fis);
try {
itemList = (ArrayList<String>) ois.readObject();
} catch (ClassNotFoundException e) {
itemList = new ArrayList<>();
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return itemList;
}
}
This gives me an error and the app crashes before it starts
I get the following error message:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 7111
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapplication/com.example.myapplication.MainActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)

ObjectInputStream ois = new ObjectInputStream(fis);
is returning null. this is not caught in try/catch as well so its crashing

Related

Loading Json data won't show

I am trying to make an app that takes data from google sheet in JSON format.
I have tried a couple of different codes to make the data simply apeare on the screen, but could not make this happen.
would be glad for ideas.
tried with a several codes using AsyncTask and saw it is not working. so tried a
different approach..
the following app is a blank page with a button, that when you click it , it suppose to make name list apear on the screen.
the JSON url:
https://myjson.dit.upm.es/api/bins/1anx
the XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:text="click me!"
android:layout_centerHorizontal="true"
android:layout_margin="50dp"/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginHorizontal="150dp"
android:padding="5dp"
android:textSize="24dp"
android:id="#+id/data"
android:text="list"/>
</ScrollView>
<ListView
android:layout_width="match_parent"
android:layout_height="0dp"
android:id="#+id/userList"
/>
</RelativeLayout>
The ActivityMain.Java :
package com.example.webdownload;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.example.webdownload.databinding.ActivityMainBinding;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
public class MainActivity extends AppCompatActivity {
ActivityMainBinding binding;
ArrayList<String> userList;
ArrayAdapter<String> listAdapter;
Handler mainHandler= new Handler();
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
initializeUserList();
binding.data.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new fetchData().start();
}
});
}
private void initializeUserList() {
userList = new ArrayList<>();
listAdapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,userList);
binding.userList.setAdapter(listAdapter);
}
class fetchData extends Thread{
String data = "";
#Override
public void run() {
mainHandler.post(new Runnable() {
#Override
public void run() {
progressDialog =new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Fetching Data");
progressDialog.setCancelable(false);
progressDialog.show();
}
});
try {
URL url =new URL("http://myjson.dit.upm.es/api/bins/1anx");
HttpURLConnection httpURLConnection=(HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line;
while ((line= bufferedReader.readLine())!= null){
data = data + line;
}
if(!data.isEmpty()){
JSONObject jsonObject = new JSONObject(data);
JSONArray users = jsonObject.getJSONArray("Users");
userList.clear();
for(int i =0;i<users.length();i++){
JSONObject names = users.getJSONObject(i);
String name = names.getString("name");
userList.add(name);
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
mainHandler.post(new Runnable() {
#Override
public void run() {
if(progressDialog.isShowing())
progressDialog.dismiss();
listAdapter.notifyDataSetChanged();
}
});
}
}
}
I Think This is happening because your JSON URL have some spelling mistake
The spelling of name (namr) is wrong
You can check your json url - Your wrong json url

Why My Recyclerview Isn't Working In An Acticvity

I need to parse json and show them on RecyclerView.. But my RecyclerView isn't working..
I need to fix this..
This is Json
Simple Json File for My app
[
{
"name": "Saif Maroof",
"roll": 978617,
"gender":"Male",
"phonenumber": 01931078639,
"StudentImage": "R.drawble.books"
},
{
"name": "Minhaj",
"roll": 978617,
"gender":"Male",
"phonenumber": 01931078639,
"studentimage": "R.drawble.books"
}
]
This is StudentInfo Activity
I think in this activity nothing gets wrong
package com.college.npc17_18.activity;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import com.college.npc17_18.MainActivity;
import com.college.npc17_18.R;
import com.college.npc17_18.adapter.StudentInfoAdapter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class StudentInfo extends AppCompatActivity {
RecyclerView recyclerView;
StudentInfoAdapter studentInfoAdapter;
RecyclerView.Adapter adapter;
// ProgressBar progressBar;
RecyclerView.LayoutManager layoutManager;
List <Object> studentInfo = new ArrayList<>();
DividerItemDecoration dividerItemDecoration;
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student_info);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// progressBar = findViewById(R.id.progress_circular_country);
recyclerView = findViewById(R.id.studentsInfoRecycleView);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
adapter = new StudentInfoAdapter(this,studentInfo);
// String jsonFileString = Utils.getJsonFromAssets(getApplicationContext(), "studentinfo.json");
// progressBar.setVisibility(View.GONE);
// studentInfoAdapter = new StudentInfoAdapter(this,studentInfo);
recyclerView.setAdapter(adapter);
addItemsFromJSON();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
private void addItemsFromJSON() {
try {
String jsonDataString = readJSONDataFromFile();
JSONArray jsonArray = new JSONArray(jsonDataString);
for (int i=0; i<jsonArray.length(); ++i) {
JSONObject itemObj = jsonArray.getJSONObject(i);
String name = itemObj.getString("name");
String roll = itemObj.getString ("roll");
String phonenumber = itemObj.getString("phonenumber");
String gender = itemObj.getString("gender");
int studentimage = itemObj.getInt("studentimage");
com.college.npc17_18.model.StudentInfo studentInfos = new com.college.npc17_18.model.StudentInfo(name,roll,phonenumber,gender,studentimage);
studentInfo.add(studentInfos);
}
} catch (JSONException | IOException e) {
Log.d(TAG, "addItemsFromJSON: ", e);
}
}
private String readJSONDataFromFile() throws IOException{
InputStream inputStream = null;
StringBuilder builder = new StringBuilder();
try {
String jsonString = null;
inputStream = getResources().openRawResource(R.raw.studentinfo);
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream, "UTF-8"));
while ((jsonString = bufferedReader.readLine()) != null) {
builder.append(jsonString);
}
} finally {
if (inputStream != null) {
inputStream.close();
}
}
return new String(builder);
}
}
This is StudentInfo Adapter
package com.college.npc17_18.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.college.npc17_18.R;
import com.college.npc17_18.model.StudentInfo;
import java.util.ArrayList;
import java.util.List;
public class StudentInfoAdapter extends RecyclerView.Adapter <StudentInfoAdapter.Viewholder> {
private List <Object> studentInfos;
Context context;
public StudentInfoAdapter(Context context, List<Object> studentInfo) {
this.studentInfos = studentInfo;
this.context = context;
}
#NonNull
#Override
public StudentInfoAdapter.Viewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.studentitem,parent,false);
return new Viewholder(view);
}
#Override
public void onBindViewHolder(#NonNull StudentInfoAdapter.Viewholder holder, int position) {
StudentInfo studentInfo = (StudentInfo) studentInfos.get(position);
holder.StudentImageId.setImageResource (studentInfo.getStudentImage());
holder.NameId.setText("Name:"+studentInfo.getNamme());
holder.RollId.setText("Roll"+studentInfo.getRoll());
holder.GenderId.setText("Gender:"+studentInfo.getGender());
holder.PhoneNumberId.setText("Phone Number:"+studentInfo.getPhoneNumber());
}
#Override
public int getItemCount() {
return studentInfos.size();
}
public class Viewholder extends RecyclerView.ViewHolder{
TextView NameId,RollId,PhoneNumberId,GenderId;
ImageView StudentImageId;
public Viewholder(#NonNull View itemView) {
super(itemView);
StudentImageId = itemView.findViewById(R.id.StudentImageId);
NameId = itemView.findViewById(R.id.NameId);
RollId = itemView.findViewById(R.id.RollId);
// CGPAId = itemView.findViewById(R.id.CGPAId);
GenderId = itemView.findViewById(R.id.GenderId);
PhoneNumberId = itemView.findViewById(R.id.PhoneNumberId);
}
}
}
This is StudentItem.xml
Layout for RecyclerView...
<?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"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:clickable="true"
android:elevation="40dp"
app:cardCornerRadius="5dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:orientation="horizontal">
<ImageView
android:id="#+id/StudentImageId"
android:layout_width="71dp"
android:layout_height="match_parent" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:orientation="vertical">
<TextView
android:id="#+id/NameId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Name"
android:textSize="18sp" />
<TextView
android:id="#+id/RollId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Roll" />
<TextView
android:id="#+id/GenderId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Gender" />
<TextView
android:id="#+id/PhoneNumberId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Phone Number" />
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
Now what do I need to do?
At the time when you instantiate an object of your adapter class
adapter = new StudentInfoAdapter(this,studentInfo);
Your adapter object is initialized with an empty studentInfo list
So, you should call adapter.notifyDataSetChanged(); in your addItemsFromJSON() method when the JSON parsing is completed.
update your adapter after you set your data
yourAdapter.notifyDataSerChanged();

I have made an application to fetch JSON data from a link. But whenever i click on the button , i don't get any data

I have made a button, on which, when i click the data is supposed to show up. But it's not. I don't know what's the problem. I don't get any errors and the app also works fine.
I have already given the internet permission so there no issue for that.
Here are the code files
MainActivity.java
package com.example.apiactivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
Button click;
public static TextView data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
click=(Button) findViewById(R.id.button);
data=(TextView) findViewById(R.id.fetcheddata);
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fetchData process= new fetchData();
process.execute();
}
});
}
}
fetchData.java
package com.example.apiactivity;
import android.os.AsyncTask;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class fetchData extends AsyncTask<Void,Void,Void> {
String data="";
String dataParsed="";
String singleParsed="";
#Override
protected Void doInBackground(Void... voids) {
try {
URL url=new URL("https://oneglobal.in/api/UserApi/Login");
HttpURLConnection httpURLConnection=(HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader= new BufferedReader(new InputStreamReader(inputStream));
String line="";
while (line!=null){
line=bufferedReader.readLine();
data= data + line;
}
JSONArray JA=new JSONArray(data);
for (int i=0;i<JA.length();i++){
JSONObject JO= (JSONObject) JA.get(i);
singleParsed= "Email:" + JO.get("Email") + "\n" + "Password:" + JO.get("Password") + "\n";
dataParsed = dataParsed+ singleParsed + "\n";
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
MainActivity.data.setText(this.data);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CLick me!"
android:id="#+id/button"
android:layout_marginBottom="10dp"
/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/button">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp"
android:textSize="24sp"
android:id="#+id/fetcheddata"
android:hint="Fetched data here"
/>
</ScrollView>
</RelativeLayout>
Whenever i click on the button, I want the json data on my screen in table view.
you have to send the user name and the password to the login api
and it is better to use retrofit or even volley to integrate with the remote api

When clicked on select item in ListView nothing happen but no error in LogCat

I have problem select item on my ListView . When I clicked nothing happen and I could not go to the next activity because the current listView not clickable.
I tried debugging code line by line but it seems like it not enter the public void onItemClick part. Why it became like that?
Here is my code,
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.Button;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class ViewAllBills extends AppCompatActivity implements ListView.OnItemClickListener {
private ListView listView;
private Button mydebtsBtn;
private String JSON_STRING;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_all_bills);
listView = (ListView) findViewById(R.id.listView);
listView.setOnItemClickListener(this);
getJSON();
myDebt();
}
//for new bill
public void myDebt() {
mydebtsBtn = (Button) findViewById(R.id.buttonMyDebt);
mydebtsBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent page1 = new Intent(ViewAllBills.this,myDebt.class);
startActivity(page1);
}
});}
private void showBills(){
JSONObject jsonObject = null;
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String, String>>();
try {
jsonObject = new JSONObject(JSON_STRING);
JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY);
for(int i = 0; i<result.length(); i++){
JSONObject jo = result.getJSONObject(i);
String id = jo.getString(Config.TAG_ID);
String desc = jo.getString(Config.TAG_DESCRIPTION);
String amo = jo.getString(Config.TAG_AMOUNT);
HashMap<String,String> bills = new HashMap<>();
bills.put(Config.TAG_ID,id);
bills.put(Config.TAG_DESCRIPTION,desc);
bills.put(Config.TAG_AMOUNT,amo);
list.add(bills);
}
} catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(
ViewAllBills.this, list, R.layout.list_item,
new String[]{Config.TAG_ID,Config.TAG_DESCRIPTION,Config.TAG_AMOUNT},
new int[]{R.id.id, R.id.description,R.id.amountBill});
listView.setAdapter(adapter);
}
private void getJSON(){
class GetJSON extends AsyncTask<Void,Void,String>{
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(ViewAllBills.this,"Fetching Data","Wait...",false,false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
JSON_STRING = s;
showBills();
}
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequest(Config.URL_GET_ALL);
return s;
}
}
GetJSON gj = new GetJSON();
gj.execute();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(ViewAllBills.this, ViewBills.class);
HashMap<String,String> map =(HashMap)parent.getItemAtPosition(position);
String billId = map.get(Config.TAG_ID).toString();
intent.putExtra(Config.BILL_ID,billId);
startActivity(intent);
}
}
This is my xml file
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true"
>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
android:background="#color/skyBlue">
<Button android:id="#+id/buttonMyDebt"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_marginTop="10dip"
android:background="#color/colorAccent"
android:textColor="#color/black"
android:textStyle="bold"
android:focusable="false"
android:text="My Debt"
android:onClick="myDebt"/>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:columnCount="3"
android:rowCount="3"
android:background="#color/softGrey"
android:layout_marginTop="5dp">
<TextView
android:id="#+id/ids"
android:layout_width="40dp"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:textStyle="bold"
android:layout_gravity="center"
android:text="ID"
/>
<TextView
android:id="#+id/descriptions"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:textStyle="bold"
android:layout_marginTop="10dp"
android:text="Bill Description"
android:layout_gravity="center"
/>
<TextView
android:id="#+id/amounts"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:textStyle="bold"
android:layout_marginTop="10dp"
android:text="Amount (RM)"
android:layout_gravity="right"
/>
</GridLayout>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="5dp"
android:id="#+id/listView" />
</LinearLayout>
</ScrollView>
This is my List_item.xml layout
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true"
android:background="#color/skyBlue"
>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnCount="3"
android:rowCount="3"
android:background="#drawable/border_style"
android:layout_marginTop="5dp">
<TextView
android:id="#+id/id"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:textStyle="bold" />
<TextView
android:id="#+id/description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
/>
<TextView
android:id="#+id/amountBill"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:layout_gravity="right"
/>
</GridLayout>
</ScrollView>
Try this:
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.Button;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class ViewAllBills extends AppCompatActivity implements ListView.OnItemClickListener {
private Button mydebtsBtn;
private String JSON_STRING;
private ListView listView;
ArrayList<HashMap<String,String>> list;
ListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_all_bills);
listView = (ListView) findViewById(R.id.listView);
list = new ArrayList<HashMap<String, String>>();
getJSON();
myDebt();
}
//for new bill
public void myDebt() {
mydebtsBtn = (Button) findViewById(R.id.buttonMyDebt);
mydebtsBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent page1 = new Intent(ViewAllBills.this,myDebt.class);
startActivity(page1);
}
});}
private void showBills(){
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(JSON_STRING);
JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY);
for(int i = 0; i<result.length(); i++){
JSONObject jo = result.getJSONObject(i);
String id = jo.getString(Config.TAG_ID);
String desc = jo.getString(Config.TAG_DESCRIPTION);
String amo = jo.getString(Config.TAG_AMOUNT);
HashMap<String,String> bills = new HashMap<>();
bills.put(Config.TAG_ID,id);
bills.put(Config.TAG_DESCRIPTION,desc);
bills.put(Config.TAG_AMOUNT,amo);
list.add(bills);
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter = new SimpleAdapter(
ViewAllBills.this, list, R.layout.list_item,
new String[]{Config.TAG_ID,Config.TAG_DESCRIPTION,Config.TAG_AMOUNT},
new int[]{R.id.id, R.id.description,R.id.amountBill});
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
}
private void getJSON(){
class GetJSON extends AsyncTask<Void,Void,String>{
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(ViewAllBills.this,"Fetching Data","Wait...",false,false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
JSON_STRING = s;
showBills();
}
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequest(Config.URL_GET_ALL);
return s;
}
}
GetJSON gj = new GetJSON();
gj.execute();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(ViewAllBills.this, ViewBills.class);
HashMap<String,String> map = list.get(position);
String billId = map.get(Config.TAG_ID).toString();
intent.putExtra(Config.BILL_ID,billId);
startActivity(intent);
}
}
If you have an active view/focusable view in your list view then it will disable your onItemClickListener.you can try to make it unfocusable by adding: android:focusable="false" ,android:focusableInTouchMode="false"to any view that is usually focusable.
I was facing the same problem and setting android:focusableInTouchMode="false" solve my problem
My problem solved..
Actually i duplicating the scrolview layout in my list_item.xml.. after i removed the scrolview and left the gridlayout only, the select list item working..

SetText is not showing text in TextView

I am trying to show the fetched string from arraylist in textview. but it is not showing the string. but when i set text="Some" in my xml file. then it shows the value.
Below i have attached my MainActivity.java and activity_main.xml file.
MainActivity.java:
package com.example.dhara.codesprint;
import android.content.res.AssetManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
//private WordDictionary dictionary;
private static final int DEFAULT_WORD_LENGTH = 3;
private static final int MAX_WORD_LENGTH = 7;
private ArrayList<String> wordList = new ArrayList<>();
private Random random =new Random();
private String currentWord;
private ArrayList<String> words;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText text7 = (EditText) findViewById(R.id.edittext);
Button checkAnswer = (Button) findViewById(R.id.button);
Button reset = (Button) findViewById(R.id.button2);
AssetManager assetManager = getAssets();
try {
InputStream inputStream = assetManager.open("words.txt");
} catch (IOException e) {
Toast toast = Toast.makeText(this, "Could not load dictionary", Toast.LENGTH_LONG);
toast.show();
}
try {
addWord();
} catch (IOException e) {
e.printStackTrace();
}
}
public void addWord() throws IOException {
BufferedReader in = new BufferedReader(new FileReader("words.txt"));
String line;
while ((line = in.readLine()) != null) {
String word = line.trim();
if (word.length() == 6) {
wordList.add(word);
}
int x,y,temp;
String str;
x=random.nextInt(wordList.size());
str=wordList.get(x);
TextView textView1 = (TextView) findViewById(R.id.textView1);
textView1.setText("Text");
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:background="#color/background"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/textView2"
android:layout_alignRight="#+id/imageView1"
android:layout_alignEnd="#+id/imageView1"
android:id="#+id/textView1"
android:layout_alignLeft="#+id/imageView1"
android:layout_alignStart="#+id/imageView1"
android:textAlignment="center"
android:textStyle="normal|bold"
android:textColor="#android:color/background_light" />
</RelativeLayout>
You're suppressing a possible error in addWord()
try {
addWord();
} catch (IOException e) {
e.printStackTrace();
}
where you just create a FileReader on a file words.txt
BufferedReader in = new BufferedReader(new FileReader("words.txt"));
Considering your test
InputStream inputStream = assetManager.open("words.txt");
the first won't find any file. You should load the asset correctly in addWord() too.
InputStreamReader fin = new InputStreamReader(assetManager.open("words.txt"));
BufferedReader in = new BufferedReader(fin);

Categories

Resources